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
Post a Comment