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

Viewed 514

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);
}
2 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);
  }
}

If you really want to achieve what you want, you should manage the threads by your own, calling to a service from the job in a separate thread.. but I don't see a reason to do that at least you're only testing and playing with Jobs at home for pet projects.

Anyway, have a look at this: https://www.baeldung.com/java-future

Related