Let's look at how you can schedule your tasks with the Spring @Scheduled annotation.
Consider the bean that's defined as follows:
@Component
public class Task {
private static final Logger log = LoggerFactory.getLogger(Task.class);
@Scheduled(fixedRate = 10000)
public void execute() {
log.info("The time is now {}", new Date());
}
}
Make sure that scheduling is enabled by adding @EnableScheduling on the Spring Boot application class:
@EnableScheduling
public class TaskSchedulingApplication implements CommandLineRunner {
Once the bean has been managed by the Spring container, @Scheduled(fixedRate = 10000) ensures that the execute method is run once every 10000 ms:
[ scheduling-1] c.mastering.spring.taskscheduling.Task : The time is now Thu Apr 25 14:15:29 IST [ scheduling-1] c.mastering.spring.taskscheduling.Task : The time is now Thu Apr 25 14:15:39 IST 2019
[ scheduling-1] c.mastering.spring.taskscheduling.Task : The time is now Thu Apr 25 14:15:49 IST 2019
[ scheduling-1] c.mastering.spring.taskscheduling.Task : The time is now Thu Apr 25 14:15:59 IST 2019
[ scheduling-1] c.mastering.spring.taskscheduling.Task : The time is now Thu Apr 25 14:16:09 IST 2019
You can customize @Schedule further with annotation attributes:
- You can use fixedDelay=10000 to indicate that the task has to be run 10000 ms after the completion of the previous task. Instead of saying that we want to run a task every 10 seconds, we are asking fixedDelay=10000 to run the task, wait for 10 seconds, and run it again.
- You can use initialDelay=20000 to specify an initial delay before the task is run for the first time.
- You can also use cron="*/8 * * * * MON"—a Unix cron expression—to specify intervals.