3

I want to wail my scheduler till my task is complete.if there is time for second schedule execution, it has to wait till previous task is not complete. I m using @Schedule in java Boot application. I want to insert data into data base in every 5 minutes but i want to hold my schedule till the inset data is not complete still there is a time for second execution.Demo Code

@Scheduled(fixedRate = 2000)
    public void scheduleTaskWithFixedRate() {
        logger.info("Fixed Rate Task :: Execution Time - {}", dateTimeFormatter.format(LocalDateTime.now()) );
    }
Reema
  • 51
  • 2
  • 2
  • 3
  • see [this](https://stackoverflow.com/questions/44644141/how-to-stop-a-scheduled-task-that-was-started-using-scheduled-annotation) – Hadi J Jan 04 '19 at 09:55
  • 2
    Check link https://www.baeldung.com/spring-scheduled-tasks and readout point number 5. – IMParasharG Jan 04 '19 at 11:20

3 Answers3

17

Use fixedDelay

fixedRate : makes Spring run the task at every n millisecond.

fixedDelay : specifically controls the next task execution time by delaying next task by n millisecond after the last execution finishes.

In code:

@Scheduled(fixedDelay=5000)
public void updateEmployeeInventory(){
    
}    

@Scheduled(fixedRate=5000)
public void updateEmployeeInventory(){
   
}
MyTwoCents
  • 7,284
  • 3
  • 24
  • 52
  • if the task block the execute thread,`fixedRate` or `fixedDelay` has no difference? – TongChen Jan 04 '19 at 10:18
  • 1
    @TongChen There is a difference. Let's say you blocked the thread for 5 Min. So next schedule will execute only after 5 Min 5 sec as per above configuration. "when the last execution finishes. " – MyTwoCents Jan 04 '19 at 14:12
  • 1
    What about cron? – आनंद Aug 19 '21 at 08:17
  • The part about `fixedRate` is in disagreement with the Baeldung article posted which says "Note that scheduled tasks don't run in parallel by default. So even if we used fixedRate, the next task won't be invoked until the previous one is done." – Adam Hughes Mar 15 '22 at 14:43
3

Instead of fixedRate, use fixedDelay:

@Scheduled(fixedDelay = 2000)

The task will run fixedDelay milliseconds one after another

Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.

Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51
0
@Scheduled(fixedDelay = 1000, initialDelay = 1000)

You should use the initialDelay prop with @scheduled annotation inorder to wait for sometime.