compare Cron Expression with current time

后端 未结 1 1093
无人及你
无人及你 2020-12-18 05:48

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 a

相关标签:
1条回答
  • 2020-12-18 06:19

    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.

    0 讨论(0)
提交回复
热议问题