java - 如何并行运行更多相同@Scheduled 作业的执行?

标签 java spring spring-boot

我有一个这样的实现,但不起作用。如您所见,作业大约需要 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@EnableAsyncSpring 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/

相关文章:

java - Spring : detached entity passed to persist

java - Spring 中没有 arg 构造函数否定了基于构造函数的 DI 优点

java - Android 版本从 2.2 更改为 4.2.2

java - 使用静态IP与桌面应用程序进行远程MySQL连接

spring - Spring EL hasRole 方法背后是哪个 Spring Java 类?

java - MySQLNonTransientConnectionException : Client does not support authentication protocol requested by server; consider upgrading MySQL client

java - 如何使用PaymentIntent(Stripe)授权资金?

spring-boot - Auth0 - 无法检索远程 JWK 集 : Read timed out

sharepoint-2010 - Sharepoint 服务器的 Java api

java 数组作为映射中的值