我正在开发一个调度项目,该项目定期执行多个作业。 我正在使用 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/