The cron expression is used to determine the dates and times that a trigger will fire and execute a job. When you create the CronTrigger instance, if you don't provide a begin time, the trigger assumes that it can begin firing as early as the current date/timedepending on the cron expression, of course. For example, if you used the expression
0 * 14-20 * * ?
the trigger would fire every minute from 2 PM to 7:59 PM, every day. As soon as you ran the CronTrigger for this expression, if it was after 2 PM, it would start firing. It would do this every day indefinitely.
On the other hand, if you wanted this schedule to not start until the next day and to continue for only a couple days, you could use the setStartTime() and setEndTime() methods on the CronTrigger to "time box" the firings. Listing 5.2 illustrates an example that confines the CronTrigger to just a couple days.
Listing 5.2. You Can Use startTime and endTime with a CronTrigger
public class Listing_5_2 { static Log logger = LogFactory.getLog(Listing_5_2.class); public static void main(String[] args) { Listing_5_2 example = new Listing_5_2(); example.runScheduler(); } public void runScheduler() { Scheduler scheduler = null; try { // Create a default instance of the Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.start(); logger.info("Scheduler was started at " + new Date()); // Create the JobDetail JobDetail jobDetail = new JobDetail("PrintInfoJob", Scheduler.DEFAULT_GROUP, PrintInfoJob.class); // Create a CronTrigger try { // cron that fires every min from 2 8pm CronTrigger trigger = new CronTrigger("MyTrigger", null, "0 * 14-20 * * ?"); Calendar cal = Calendar.getInstance(); // Set the date to 1 day from now cal.add(Calendar.DATE, 1); trigger.setStartTime(cal.getTime()); // Move ahead 2 days to set the end time cal.add(Calendar.DATE, 2); trigger.setEndTime(cal.getTime()); scheduler.scheduleJob(jobDetail, trigger); } catch (ParseException ex) { logger.error("Couldn't parse cron expr", ex); } } catch (SchedulerException ex) { logger.error(ex); } } } |
The example in Listing 5.2 uses the java.utl.Calendar to select a begin time and end time period for the trigger. In the case of this example, the trigger will start firing the day after it's scheduled and will fire for only two days after it starts to fire.
Use the startTime and endTime properties of the CronTrigger just as you would for SimpleTriggers.
Scheduling in the Enterprise
Getting Started with Quartz
Hello, Quartz
Scheduling Jobs
Cron Triggers and More
JobStores and Persistence
Implementing Quartz Listeners
Using Quartz Plug-Ins
Using Quartz Remotely
Using Quartz with J2EE
Clustering Quartz
Quartz Cookbook
Quartz and Web Applications
Using Quartz with Workflow
Appendix A. Quartz Configuration Reference