我有一个这样的实现,但不起作用。如您所见,作业大约需要 5 秒,并且应以 fixedRate
1 秒运行。这意味着应该有大约 5 个作业并行运行,但 Spring 会等待完成一项作业,然后再开始另一项作业......
如果我添加具有相同 和 参数的第二个 @Scheduled 作业“schedule2”,则我有 2 个不同的作业并行运行,但绝不是相同的作业。有可能以某种方式实现这一目标吗?
@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);
}
最佳答案
在这种情况下,每个计划任务将永远并行运行。这是因为任务花费的时间比给定的固定速率更长。为什么?因为ScheduledExecutorService#scheduleAtFixedRate
被调用,正如文档所说(粗体是我的):
... If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
解决此问题的一种方法是使用 @Async
和 @EnableAsync
。 Spring docs 中提供了许多示例。 :
@EnableAsync
public class Example {
@Async
@Scheduled(fixedRate = 1000)
public void schedule1() throws InterruptedException {
Thread.sleep(5000);
}
}
关于java - 如何并行运行更多相同@Scheduled 作业的执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58536056/