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);
}
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With