How wait @Scheduled till previous task is not finished?

Viewed 11775

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()) );
    }
3 Answers

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(){
   
}

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.

@Scheduled(fixedDelay = 1000, initialDelay = 1000)

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

Related