Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 505
PS Kumar Avatar asked Nov 04 '25 08:11

PS Kumar


1 Answers

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

like image 120
ck1 Avatar answered Nov 05 '25 23:11

ck1