I am implementing scheduled tasks using Spring, and I see there are two types of config options for time that schedule work again from the last call. What is the difference between these two types?
@Scheduled(fixedDelay = 5000) public void doJobDelay() { // do anything } @Scheduled(fixedRate = 5000) public void doJobRate() { // do anything }
Schedule a Task at Fixed Delay In this case, the duration between the end of the last execution and the start of the next execution is fixed. The task always waits until the previous one is finished. This option should be used when it's mandatory that the previous execution is completed before running again.
Spring Core. Spring provides excellent support for both task scheduling and asynchronous method execution based on cron expression using @Scheduled annotation. The @Scheduled annotation can be added to a method along with trigger metadata.
The schedule (TimerTask task, Date time) method of Timer class is used to schedule the task for execution at the given time. If the time given is in the past, the task is scheduled at that movement for execution.
The @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. @SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.
In code:
@Scheduled(fixedDelay=5000) public void updateEmployeeInventory(){ System.out.println("employee inventory will be updated once only the last updated finished "); /** * add your scheduled job logic here */ } @Scheduled(fixedRate=5000) public void updateEmployeeInventory(){ System.out.println("employee inventory will be updated every 5 seconds from prior updated has stared, regardless it is finished or not"); /** * add your scheduled job logic here */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With