【问题标题】:How wait @Scheduled till previous task is not finished?如何等待@Scheduled 直到上一个任务没有完成?
【发布时间】:2019-05-30 21:09:54
【问题描述】:

我想等待我的调度程序直到我的任务完成。如果有时间执行第二次调度,它必须等到前一个任务没有完成。 我在 java Boot 应用程序中使用@Schedule。 我想每 5 分钟向数据库中插入一次数据,但我想保留我的计划,直到插入数据不完整,仍然有时间进行第二次执行。演示代码

@Scheduled(fixedRate = 2000)
    public void scheduleTaskWithFixedRate() {
        logger.info("Fixed Rate Task :: Execution Time - {}", dateTimeFormatter.format(LocalDateTime.now()) );
    }

【问题讨论】:

标签: java spring spring-boot spring-mvc


【解决方案1】:

使用fixedDelay

fixedRate : 让 Spring 定期运行任务,即使最后一次调用可能仍在运行。

fixedDelay : 专门控制最后一次执行结束时的下一次执行时间。 在代码中:

@Scheduled(fixedDelay=5000)
public void updateEmployeeInventory(){

}    

@Scheduled(fixedRate=5000)
public void updateEmployeeInventory(){

}

【讨论】:

  • 如果任务阻塞执行线程,fixedRatefixedDelay没有区别?
  • @TongChen 有区别。假设您将线程阻塞了 5 分钟。因此,根据上述配置,下一个计划将仅在 5 分 5 秒后执行。 "当最后一次执行完成时。"
  • cron 呢?
【解决方案2】:

fixedDelay代替fixedRate

@Scheduled(fixedDelay = 2000)

任务将一个接一个地运行fixedDelay毫秒

在上一次调用结束和下一次调用开始之间以毫秒为单位的固定时间段内执行带注释的方法。

【讨论】:

  • 我做一个demo,fixedRate或者fixedDelay都可以,为什么?:
  • 有人能回答一下spring“cron表达式”是否像“fixedDelay”一样等待任务完成?
【解决方案3】:
@Scheduled(fixedDelay = 1000, initialDelay = 1000)

您应该使用带有@scheduled 注释的 initialDelay 属性来等待某个时间。

【讨论】:

    猜你喜欢
    • 2012-07-23
    • 2018-08-20
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 2011-03-17
    相关资源
    最近更新 更多