Using Quartz CronTrigger to generate filename timestamps for scheduling
Februar 6th, 2007 | By Christoph in Allgemein, Software-Development | No Comments »Today we had to generate files which will be importet by another 3rd party system, to import certain XML files from our system.
The other system expected the filenames to follow the a convention:
PREFIX_TIMESTAMP.xml
The timestamp had to be a date following some scheduling rules:
If the other system expects an import file at 10:00 a.m. then the filename has to have PREFIX_20070106-10:00.xml
But now I wanted to have some flexibilty in creating the timestamp.
Our export should run every to hours starting at 9:45 a.m. and the filenames should be
10:00.xml
12:00.xml
14:00.xml
ans so on.
This is when the CronTrigger by the Quartz Scheduler comes into play:
I use the CronTrigger to generate the Timestamps for the filename using this utility function:
public static Calendar getSplitTimeStringByCronExpression(String cronTrigger)
{
Assert.notNull(cronTrigger);
Calendar nextRunTime = Calendar.getInstance();
CronTrigger ct = new CronTrigger();
try {
ct.setCronExpression(cronTrigger);
ct.setStartTime(nextRunTime.getTime());
org.quartz.Calendar quartzCal = new org.quartz.impl.calendar.BaseCalendar();Date firstFireTime = ct.computeFirstFireTime(quartzCal);
Date nextFireTime = ct.getNextFireTime();System.out.println(“firstFireTime: ” + firstFireTime);
System.out.println(“nextFireTime: ” + nextFireTime);
nextRunTime.setTime(nextFireTime);} catch (ParseException e) {
e.printStackTrace();
}
return nextRunTime;
}
An example app would be:
public static void main(String[] args) {
String cronExpression = “0 00 08,10,12,14,16,18,20,22 * * ?”;
Utils.getSplitTimeStringByCronExpression(cronExpression);
}
Calling this function at 9:45 a.m. will result in the output:
firstFireTime: Tue Feb 06 10:00:00 CET 2007
nextFireTime: Tue Feb 06 10:00:00 CET 2007
This is pretty helpful and powerfull, because I can change the behaviour just by defining the cronExpression using this definition
in the class CronTrigger