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

mirec :

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);
}
Maroun :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322461&siteId=1