Skip to main content

Scheduler(Task Executor) In Spring Boot



WHAT IS A SCHEDULER?

      Firstly know about what is scheduling. Scheduling is a process that executing a task in a certain time period. A scheduler is a tool, the main objective is to implement the scheduling process. Mainly scheduler is used to perform the batch task for the repeated manner and perform the action of task without any outer other events.

IMPLEMENTATION OF SCHEDULER IN SPRING BOOT:


       In spring boot we can implement scheduler in multiple ways but here we use the annotation to implement the scheduler. In spring boot we can implement scheduler using @Scheduled annotation. The @Scheduled annotation internally uses the TaskScheduler interface to schedule a task. To enable the @Scheduled annotation we must use @EnableScheduling annotation in the Configuration file.

       Let's start with an example of task scheduler. Her we use STS(spring tool suite) to build the spring boot project. First, build a project with web configuration.

PROJECT STRUCTURE:



















MAVEN DEPENCENIES:

pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

         This dependency already presents in the pom.xml file if we build project in web type module. if it doesn't exist then add in pom.xml.

           Configure the scheduling in the main class and add the @EnableScheduling annotation. This annotation can provide the capabilities to activate the task scheduler to execute the task.

 DeveloperVillageApplication.java


package com.dv;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication(scanBasePackages = { "com.dv"})
@EnableScheduling
public class DevelpoerVillagerApplication {

public static void main(String[] args) {
SpringApplication.run(DevelpoerVillagerApplication.class, args);
}

}

          After enable scheduling in parent class then we need to annotate the method which we want to execute in the time period. So in the above example, we create a class to declare a method which prints the time in which this method is executed and in that method, we perform some mathematical operations. Let's create the class:

DVController.java


package com.dv;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class DVController {

private static Logger logger = LoggerFactory.getLogger(DVController.class);
int addNumber = 0;
int multiplicationNumber = 5;
@Scheduled(cron="0/5 * * * * ?")
public void executeTaskSchedulerMethod() {
logger.info("In DVController calss executeTaskSchedulerMethod method. with the execution start time:{}",new Date(System.currentTimeMillis()));
logger.info("Current value of addNumber = {}",addNumber);
logger.info("Current value of multiplicationNumber = {}",multiplicationNumber);
addNumber = addNumber+5;
multiplicationNumber = multiplicationNumber * 5;
logger.info("After increment, value of addNumber = {}",addNumber);
logger.info("After multiply, value of multiplicationNumber = {}",multiplicationNumber);
}
}

           In the above example we create a class, named as DVController and declare a method named as executeTaskSchedulerMethod().In that method, you can implement your business logic. Here I simply print a statement and make some addition  and multiplication operations.

          In above we annotated the method using @Scheduled which is execute that method in a certain time period and here we use the cron expression to instruct the @Scheduled annotation when to execute the annotated method. Later we discuss about cron expression in detail but for reference now you can check here.

        In the above, I schedule the scheduler execute in every 5 seconds.We can use a different way to instruct the scheduler to schedule the task.let's discuss all of that process.

1.Cron Expression
2.Fixed Rate
3.Fixed Delay

1.CRON Expression:

 @Scheduled(cron="0/5 * * * * ?")

public void executeTaskSchedulerMethod() {
       //Code for execution
}

            In cron expression, there are certain cron pattern is provided, which is instantiate the cronTrigger which instruct the scheduled annotation to execute the operations. In cron expression scheduler wait to start timer to execute second task until the first task is not complete. Most advantage of cron expression we can set a time when the trigger execute, we can use this both repeated and specific time task execution.

2.Fixed Rate:


@Scheduled(fixedRate = 1000)
public void executeTaskSchedulerMethod() {
       //Code for execution
}

           Fixed Rate work as the cron expression but in fix rate, the scheduler doesn't wait for the completion of the first task to execute the second task. It repeatedly executes the task in the time period. in the fixed rate the values of time are in milliseconds. so above scheduler execute in every 1 sec.

3.Fixed Delay:

@Scheduled(fixedDelay = 1000, initialDelay = 5000)
public void executeTaskSchedulerMethod() {
           //Code for exection
}

           Fixed Delay similarly work as fixed rate but the major difference is here fixed delay wait for the first process completely execute after that it executes the second process in the declared time period. In fixed delay, @scheduled has 2 params .fixedDelay declare the time interval between the two processes and initialDelay define how much time interval is maintained in first process execution after the application is started.

OUTPUT:

           This is the output of cron expression scheduler, which is execute in every 5 second.


Comments

Popular posts from this blog

Send FTL In Email Using Spring Boot

                  In this topic, we discuss mail protocol and how to send email using mail library and how can we sent an email with more dynamic and with some more graphical interface and it's really looking good than the traditional email content. Here we use FTL to make email a more graphical experience. We try to show the example of this topic as possible as an easy way. so without wasting any time let's start the topic. WHAT IS FTL AND WHAT'S THE BENEFITS?          FTL(Free marker template) is a Java-based template language which is used to make the more dynamic and graphical experience on screen. FTL discovered by Apache foundation. It focuses on java based dynamic template design. Free marker template file extension is .ftl which is approx. as same as HTML code but the major difference is, we can send the data from Java source classes to show dynamic content. It's the main focus on MVC architec...

QR Code Generate using zxing in spring boot

WHAT IS QR CODE AND HOW TO GENERATE QR CODE USING JAVA:           QR Code stands for Quick Response Code first design in Japan in 1994. The QR code is the trademark for a type of matrix barcode. The main purpose is to store information and is easily read by the advanced mobile system. The QR code is the two-dimensional bar code which store the piece of information.in the QR code information are encoded in 4 standardized encoding mode (numeric, alphanumeric, byte/binary, and kanji)    to store data efficiently. In Java, we can generate a QR code using zxing API provided by Google .zxing API support 4000 characters to encode. So without wasting any time let begin with an example for a better preference. PROJECT STRUCTURE: MAVEN DEPENDENCIES:        Put the dependencies on pom.xml pom.xml: <!-- https://mvnrepository.com/artifact/com.google.zxing/core --> ...