spring - 如何获取Spring调度下一次运行时间?

标签 spring scheduled-tasks job-scheduling spring-scheduled

我正在开发一个调度项目,该项目定期执行多个作业。 我正在使用 cron 调度,如下例所示。作业成功执行,没有任何问题。 但是,对于一个要求,我想计算并保留数据库中计划作业的下一次运行时间。 是否有解决方案可以获取以下配置的作业的下一个和上一个触发时间?

配置示例:

import java.util.Date;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
public class DemoServiceBasicUsageCron
{   
    @Scheduled(cron="1,3,30,32 * * * * ?")
    public void demoServiceMethod()
    {
        System.out.println("Curent date time is - "+ new Date());
    }

}

最佳答案

您可以将 CronExpression 用于 Spring Framework 5.3 及更高版本。对于旧版本,请使用CronSequenceGenerator。他们俩都有相同的方法。但是 CronSequenceGenerator 已被弃用。

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.support.CronExpression;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

@Component
public class MyJob {

    public static final String CRON_EXPRESSION = "0 0 5 * * *";

    @PostConstruct
    public void init() {
        //Update: Resolve compile time error for static method `parse`
        CronExpression cronTrigger = CronExpression.parse(CRON_EXPRESSION);

        LocalDateTime next = cronTrigger.next(LocalDateTime.now());

        System.out.println("Next Execution Time: " + next);
    }

    @Scheduled(cron = CRON_EXPRESSION)
    public void run() {
        // Your custom code here
    }
}

关于spring - 如何获取Spring调度下一次运行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43766183/

相关文章:

java - 创建名称为“scopedTarget.contextHeadersBuilder”的 bean 时出错

java - Spring MVC : Bad request (parameter missing) on file upload even when required parameters are present

android - 如何将 Bundle 转换为 PersistableBundle?

c - 循环时间调度中的时间片

hadoop - Oozie 未启动

java - 访问 SecurityContextHolderAwareRequestWrapper 实例?

java - 在多个服务器上使用 Spring Security 和 Spring Redis Session

windows - 在不弹出命令提示符的情况下以批处理模式运行 R 脚本

coldfusion - 如何找出计划任务的下一次运行时间?

c# windows 服务还是普通程序?