Search code examples
javacronquartz-schedulercrontrigger

error when using cronTrigger with an expression that contains a year value


I'm observing a strange behavior scheduling a job in Quartz using a CronTrigger that contains a year value.

Here is how I am creating a trigger and scheduling a job with it:

CronTrigger trigger =  cronJobTriggerFactory.getObject();
trigger.setName(triggerName);
trigger.setGroup(triggerGroupName);
trigger.setCronExpression(cronSchedule);
trigger.setVolatility(false);

JobDetail job = schedulableJobFactory.getObject();
job.setName(jobName);
job.setGroup(jobGroupName);
job.setVolatility(false);
job.setDurability(true);
Date scheduleTime1 = scheduler.scheduleJob(job, trigger);
logger.info(job.getKey() + " will run at: " + scheduleTime1);

and then in my unit test I determines the "now" date, add 5 minutes to it, calculate cron expression for this date/time and call my main class schedule a job with this schedule. Here is the out put of the unit test that shows which cron expression is passed :

NotificationSchedulerTest - Today is: 9 May 2012 05:32 PM
NotificationSchedulerTest - 5 min later is: 9 May 2012 05:37 PM
NotificationSchedulerTest - cron schedule is: 0 37 17 * 4 ? 2012

However, when trying to schedule a job with this cron expression - I'm getting the following error:

org.quartz.SchedulerException: Based on configured schedule, the given trigger will never fire.

As you can see, the date is in the future relative to the date/time I am running the test... So, it should not be a problem with trying to schedule a job to run at a time in the past.

Now the next strange thing: notice that I do specify the year value in my cron expression: " 0 37 17 * 4 ? 2012".

If I modify generation of the cron expression and leave the year field as unspecified (since it is optional): " 0 37 17 * 4 ?" Then the scheduling DOES succeed, however, the scheduler shows that the next time the job will fire is in the year 2013! (one year later.... - and of course I cannot wait that long to verify it is fired...):

NotificationSchedulerTest - Today is: 9 May 2012 06:11 PM
NotificationSchedulerTest - 5 min later is: 9 May 2012 06:16 PM
NotificationSchedulerTest - cron schedule is: 0 16 18 * 4 ?
...
NotificationScheduler - myJobKey will run at: Mon Apr 01 18:16:00 EDT 2013

Am I missing something in these cron expressions?


Solution

  • Months in cron expressions are 1-based. That's why 0 37 17 * 4 ? 2012 is never executed: today is 10th of May and you want it to run on every day of April. When you remove the year it prints next scheduled date in 2013, but in April! myJobKey will run at: Mon Apr 01 18:16:00 EDT 2013.

    Obviously your expression should be:

    0 37 17 * 5 ? 2012
    

    or to avoid confusion in the future:

    0 37 17 * May ? 2012