Scheduling tasks in spring boot
1. Enabling scheduling in spring boot
Spring provides support for scheduling tasks which you can enable by just adding the annotation @EnableScheduling on any of your @Configuration class.
@Configuration
@EnableScheduling
public class ScheduleConfig {
}
2. Cron expression
A cron expression is used to schedule a task. Cron expression consists of six fields in the following order
second, minute, hour, day of the month, month, day(s) of week
To schedule a task using cron just add @Scheduled(cron = "* * * * * *")
annotation on any method you need to schedule.
@Scheduled(cron = "*/10 * * * * *")
public void doSomething() {
// do something here
}
The */10
in the @Scheduled
annotation tells the spring boot to execute this method after every 10 seconds.
Note: The method you need to schedule should return void and should not accept any parameters.
2.1. Some examples of a cron expression
Below are some cron expression examples for scheduling tasks:
"0 0 * * * *"
= the top of every hour of every day.
"0 0 */1 * * *"
= every one hour.
"0 0 8-10 * * *"
= 8, 9, and 10 o'clock of every day.
"0 0/30 8-10 * * *"
= 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
"0 0 8-16 * * MON-FRI"
= on the hour eight-to-four weekdays
"0 0 0 01 01 ?"
= every new year at midnight
3. Fixed Delay scheduling
You can also schedule a task that waits for the fixed time after the execution of the last task before the execution of the next task starts
@Scheduled(fixedDelay = 2000)
public void doSomething() {
// do something
}
This task will execute after a delay of 2 seconds from the time of completion on the last task.
4. Fixed Rate scheduling
If you want to run a task periodically, you can use fixed rate to specify the time period in milliseconds after which the task needs to be executed periodically.
@Scheduled(fixedRate = 5000)
public void doSomething() {
// do something
}
This task will run after every 5 seconds.
5. Conclusion
In this tutorial, we saw how to schedule a task in spring boot and how to schedule a task using a cron expression.