I'm using the Quartz CronTrigger facility to parse cron schedule format strings to determine when a specific job should run. I'm not actually using Quartz to schedule the job though.
There is a method in CronTrigger called getFireTimeAfter(Date) which gives the next time the job will fire after the given date. This works well when the supplied date is now or in the future. But it doesn't seem to work if the date is in the past.
Date currTime = new Date();
CronTrigger tr = new CronTrigger();
tr.setCronExpression("0 0 23 3,18 * ? *");
Date nextFireAt = tr.getFireTimeAfter(currTime);
System.out.println("Reference time: " + currTime);
System.out.println("Next fire after reference time: " + nextFireAt);
Which is a cron schedule to fire at 23:00 on the 3 and 18 of every month. So for example, if I did this today (August 11), I see:
Reference time: Thu Aug 11 10:04:25 MDT 2011
Next fire after reference time: Thu Aug 18 23:00:00 MDT 2011
But if I set the reference date to the past, it gives me the same next fire time.
Reference time: Wed Dec 31 17:00:00 MST 1969
Next fire after reference time: Thu Aug 18 23:00:00 MDT 2011
I was expecting the output to be:
Reference time: Wed Dec 31 17:00:00 MST 1969
Next fire after reference time: Wed Aug 3 23:00:00 MDT 2011
Is the method just not intended to work that way or am I doing something wrong?
Thanks!
What you really want to use the the CronExpression object directly not the CronTrigger. As you discovered, it won't calculate next run times in the past... but CronExpression will!
CronExpression has the method: getNextValidTimeAfter. This is what you want.