Scheduling in Springboot
Job scheduling is a crucial aspect of many applications, especially when it comes to automating repetitive tasks, batching large sets of operations, or ensuring that certain activities run at specific intervals. In the vast ecosystem of Spring Boot, the framework offers seamless ways to handle job scheduling, making it easier for developers to integrate it into their applications.
Spring Boot provides the ability to schedule tasks for execution at a given time period with the help of @Scheduled annotation. This article provides a step by step guideline on how we can schedule tasks to run in a spring boot application
Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Steps to implementation of Scheduling in Springboot
1. Specifying @EnableScheduling annotation in the Spring Boot application class.
2. Creating a @Component class Scheduler which defines the method scheduleTask() for scheduling a task using the @Scheduled annotation. The method scheduleTask() in Scheduler class simply prints the date and time at which the task is running.
example of Scheduler class
@Component
public class MyScheduledTask {
Recommended by LinkedIn
@Scheduled(fixedRate = 5000)
public void scheduleTask() {
System.out.println("Running Scheduled Task every 5 seconds!");
}
}
Schedule using cron-expressions
The cron element specified in the @Scheduled annotation allows defining cron-like expressions to include triggers on the second, minute, hour, day of the month, month, and day of the week.
Parameters which are we can pass as argument in @Scheduled
1. Cron: A cron-like expression, extending the usual UN*X definition to include triggers on the second, minute, hour, day of month, month, and day of week.
2. fixedDelay: Execute the annotated method with a fixed period between the end of the last invocation and the start of the next.
3. fixedDelayString: Execute the annotated method with a fixed period between the end of the last invocation and the start of the next.
4. fixedRate: Execute the annotated method with a fixed period between invocations.
5. fixedRateString: Execute the annotated method with a fixed period between invocations.
6. initialDelay: Number of units of time to delay before the first execution of a fixedRate() or fixedDelay() task.
7. initialDelayString: Number of units of time to delay before the first execution of a fixedRate() or fixedDelay() task.
8. scheduler: A qualifier for determining a scheduler to run this scheduled method on.
9. timeUnit: The TimeUnit to use for fixedDelay(), fixedDelayString(), fixedRate(), fixedRateString(), initialDelay(), and initialDelayString().
10. zone: A time zone for which the cron expression will be resolved.