PS Kumar
PS Kumar

Reputation: 2436

Is Spring Boot @Scheduled synchronous or asynchronous?

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?

Upvotes: 4

Views: 6846

Answers (1)

ck1
ck1

Reputation: 5443

@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.

Upvotes: 13

Related Questions