In the real world, job schedules are normally much more complex than SimpleTriggers will support. CronTriggers can be used to specify very complicated schedules, which is good because those are usually the ones we find we need. Before we get into the details of what makes a CronTrigger tick, let's look at an example. Listing 5.1 shows an example of using a CronTrigger (along with a Quartz cron expression) to schedule the PrintInfoJob from previous examples. For the most part, this code is identical to the examples in the previous chapter. The only difference is that we are using a CronTrigger instead of a SimpleTrigger. Because of that, we have to supply it with a cron expression.
Listing 5.1. Simple Use of CronTrigger to Schedule a Job
public class Listing_5_1 { static Log logger = LogFactory.getLog(Listing_5_1.class); public static void main(String[] args) { Listing_5_1 example = new Listing_5_1(); 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 { // CronTrigger that fires @7:30am Mon - Fri CronTrigger trigger = new CronTrigger("CronTrigger", null, "0 30 7 ? * MON-FRI"); scheduler.scheduleJob(jobDetail, trigger); } catch (ParseException ex) { logger.error("Error parsing cron expr", ex); } } catch (SchedulerException ex) { logger.error(ex); } } } |
The example in Listing 5.1 uses the following cron expression:
0 30 7 ? * MON-FRI
When interpreted by the Scheduler, this causes the trigger to fire at 7:30 AM Monday through Friday. Let's look at the format of the cron expression for Quartz CronTriggers.
The Cron Expression Format |
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