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

查看:2758
本文介绍了将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表达式将始终引用将来的有效时间。对此的一个警告是,石英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 实例,然后请求它下一个有效的未来时间; a 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天全站免登陆