3
votes

In our project we are using Spring Boot 2.1.3.Release, for scheduler job we used @Scheduled at method level.

@Scheduled(fixedRate = 1000)
public void fixedRateSchedule() {
    System.out.println(
      "Fixed rate task - " + System.currentTimeMillis() / 1000);
}

The fixed rate does not wait previous task to complete.

@Scheduled(fixedDelay = 1000)
    public void fixedDelaySchedule() {
        System.out.println(
          "Fixed delay task - " + System.currentTimeMillis() / 1000);
    }

The fixedDelay, task always waits until the previous one is finished.

@Scheduled(cron = "0 0/5 * * * ?")
        public void fixedDelaySchedule() {
            System.out.println(
              "cron  task - " + System.currentTimeMillis() / 1000);
        }

The above cron will execute every five minutes, my question is: will the @scheduled cron wait for the previous task to complete before triggering the next job or not?

1
@Scheduled methods by default use a thread pool with size 1, so only one method will be executed at a time. You can change this by configuring a TaskScheduler bean. - ck1
@ck1: so my method should be execute once my previous task complete right? - PS Kumar
That’s correct, it just won’t execute concurrently. - ck1

1 Answers

7
votes

@Scheduled methods are executed asynchronously, but by default Spring Boot uses a thread pool of size 1, so each method will be executed one at a time.

To change this, add the following to your Spring Boot configuration:

@Bean
public TaskScheduler taskScheduler() {
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.setPoolSize(5);
    return taskScheduler;
}

Here's a link to the source code for ThreadPoolTaskScheduler.