Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run more executions of same @Scheduled jobs in parallel?

Tags:

I have an implementation like this which doesn't work. As you see, job takes ~5sec and should run on fixedRate 1sec. That means there should be ~5jobs running in parallel but Spring wait to finish a job before starts another one... If I add second @Scheduled job 'schedule2' with the same and parameters, I have 2 different jobs running in parallel but never the same job. Is it somehow possible to achieve this?

@Scheduled(fixedRate = 1000)
private void schedule1() {
    int index = atomicInteger1.addAndGet(1); 
    logger.info("Run Schedule1 nr.{} started at: {}", index, LocalDateTime.now());
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        logger.info("Schedule1 nr.{} finished at: {}", index, LocalDateTime.now());
    }
}

@Bean(destroyMethod = "shutdown")
public Executor taskExecutor() {
    return Executors.newScheduledThreadPool(10);
}
like image 909
mirec Avatar asked Oct 24 '19 07:10

mirec


1 Answers

Each scheduled task will never run in parallel in this case. That's because the task takes longer than the given fixedRate. Why? Because ScheduledExecutorService#scheduleAtFixedRate is called, and as the documentation says (bolded is mine):

... If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

One way of solving this is by using @Async and @EnableAsync. Many examples are available in the Spring docs:

@EnableAsync
public class Example {

  @Async
  @Scheduled(fixedRate = 1000)
  public void schedule1() throws InterruptedException {
    Thread.sleep(5000);
  }
}
like image 170
Maroun Avatar answered Oct 18 '22 16:10

Maroun