Scheduled
- dependency:
spring-boot-starter-data-jpa
- Use
@Scheduled on method to define the task
- Use
@EnableScheduling on main method to enable @Scheduled
@Component
public class MyScheduledTask {
@Scheduled(fixedRate = 5000)
public void runTask() {
System.out.println("Running Scheduled Task every 5 seconds!");
}
}
// -------------------------------------------------------------
@SpringBootApplication
@EnableScheduling
public class SchedulingTasksApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingTasksApplication.class);
}
}
- More Options:
@Scheduled(fixedRate = 5000): 5ms
@Scheduled(fixedDelay = 5000)
@Scheduled(cron = "0 0 * * * ?"): hourly run task
- Considerations in distributed systems
- multiple microservices try to run the same task, hence more than one task gets executed
- Use distributed locks, spring boot supports:
- Redis:
spring-boot-starter-data-redis
- Zookeeper, Hazelcast etc.
- The timing is off because of timezone difference in microservices
- It covers only simple cases. For more complex cases you can use distributed job scheduler like
Quartz
- Dependency:
spring-boot-starter-quartz
- ref: https://medium.com/hprog99/mastering-job-scheduling-in-spring-boot-from-basics-to-best-practices-74ab938d80fa