Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

java - compare Cron Expression with current time

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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();
    }
}

Here's a link to the Quartz CronExpression API.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...