Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...