如何获得下一个 运行 时间 Spring 调度?

How to get next run time Spring Scheduling?

我正在从事一个定期执行多个作业的计划项目。 我正在使用 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());
    }

}

希望您使用的是 Quartz。你可以尝试这样的事情。

CronExpression exp = new CronExpression("1,3,30,32 * * * * ?");
exp.getNextValidTimeAfter(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
    }
}