mir*_*rec 5 java spring spring-boot
我有一个这样的实现,但不起作用。如您所见,作业大约需要 5 秒,运行时间应为fixedRate1 秒。这意味着应该有大约 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);
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,每个计划任务永远不会并行运行。那是因为任务花费的时间比给定的要长fixedRate。为什么?因为ScheduledExecutorService#scheduleAtFixedRate被称为,正如文档所说(粗体是我的):
...如果该任务的任何执行时间超过其周期,则后续执行可能会延迟开始,但不会并发执行。
解决此问题的一种方法是使用@Async和@EnableAsync。Spring 文档中提供了许多示例:
@EnableAsync
public class Example {
@Async
@Scheduled(fixedRate = 1000)
public void schedule1() throws InterruptedException {
Thread.sleep(5000);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1096 次 |
| 最近记录: |