将 Cron 表达式与当前时间进行比较 [英] compare Cron Expression with current time

查看:86
本文介绍了将 Cron 表达式与当前时间进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个调度程序并使用石英库.我想检查cron表达式时间是否指的是未来的时间,否则触发器根本不会被执行.有没有什么办法可以比较cron表达式时间和java中的当前时间.

I am designing a scheduler and using quartz library. I want to check whether cron expression time refer to the time in the future, Otherwise trigger won't be executed at all. Is there any way of comparing cron expression time with current time in java.

推荐答案

需要考虑的是,标准的有效 cron 表达式将始终引用未来的有效时间.对此的一个警告是 Quartz cron 表达式可能包含一个可选的年份字段,该字段可以是过去也可以是未来.

Something to consider is that a standard valid cron expression will always refer to a valid time in the future. The one caveat to this is that Quartz cron expressions may include an optional year field, which could be in the past as well as the future.

要检查表达式的有效性,您可以构建一个 CronExpression 实例,然后询问它下一个有效的未来时间;null 表示该表达式没有有效的未来时间.这是一个快速的单元测试示例:

To check the validity of the expression, you can build a CronExpression instance then ask it for the next valid future time; a null indicates that there is no valid future time for the expression. Here's a quick unit test example:

@Test
public void expressionTest() {
    Date date;
    CronExpression exp;
    // Run every 10 minutes and 30 seconds in the year 2002
    String a = "30 */10 * * * ? 2002";      
    // Run every 10 minutes and 30 seconds of any year
    String b = "30 */10 * * * ? *"; 
    try {
        exp = new CronExpression(a);
        date = exp.getNextValidTimeAfter(new Date());
        System.out.println(date);       // null
        exp = new CronExpression(b);
        date = exp.getNextValidTimeAfter(new Date());
        System.out.println(date);       // Tue Nov 04 19:20:30 PST 2014
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

这是 Quartz <代码的链接>CronExpression API.

Here's a link to the Quartz CronExpression API.

这篇关于将 Cron 表达式与当前时间进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆