Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quartz CronTrigger - Getting next fire time

Tags:

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!

like image 539
cambo Avatar asked Aug 11 '11 16:08

cambo


2 Answers

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.

like image 71
Jason Clawson Avatar answered Sep 27 '22 19:09

Jason Clawson


In Spring you can follow the same approach they use in their integration tests. CronTriggerTests

CronTrigger trigger = new CronTrigger(); trigger.setCronExpression("0 0 23 3,18 * ? *"); SimpleTriggerContext triggerContext = new SimpleTriggerContext(); triggerContext.update(null, null, new Date()); Date nextFireAt = trigger.nextExecutionTime(triggerContext); 
like image 33
ibai Avatar answered Sep 27 '22 18:09

ibai