ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Scheduling Jobs in a Java Web Application
Pages: 1, 2, 3

Other Timing Configurations

Quartz provides many ways in which to schedule work. The CronTrigger is perhaps the most sophisticated, but there are several others. Most of the trigger mechanisms can be created using the TriggerUtils class provided by Quartz. Here are some other common examples of other Triggers in action. As the old saying goes, there's more than one way to skin a cat.



Triggers that Fire Every Day at 2:22 a.m.

// option 1: using makeDailyTrigger
Trigger trigger = TriggerUtils.makeDailyTrigger(2, 22);
trigger.setName("trigger1");
trigger.setGroup("group1");

// option 2: using CronTrigger
Trigger trigger = new CronTrigger("trigger1", "group1");
trigger.setCronExpression("0 22 2 * * ?");

A Trigger that Executes Every Five Seconds

/* option 1: makeSecondlyTrigger
 * Note that this will create a trigger that starts immediately.
 * To control the start time, use trigger.setStartTime(Date)
 */
Trigger trigger = TriggerUtils.makeSecondlyTrigger(5);
trigger.setName("MyFiveSecondTrigger");
trigger.setGroup("MyTriggerGroup");


 /* option 2: set repeat count and interval on simple trigger
 * Note that this will create a trigger that starts immediately.
 * To control the start time, use trigger.setStartTime(Date)
 */
Trigger trigger = new SimpleTrigger("trigger1", "group1");
trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
trigger.setRepeatInterval(5000L); // milliseconds

Running a Job at Intervals

Trigger trigger = new SimpleTrigger("trigger1", "group1");
// 24 hours * 60(minutes per hour) *
// 60(seconds per minute) * 1000(milliseconds per second)
trigger.setRepeatInterval(24L * 60L * 60L * 1000L);

Conclusion

In this demonstration, we've only scratched the surface to what the Quartz framework can do. Keep in mind that Java 5 and J2EE 5 also have scheduling mechanisms, but they aren't as flexible and as easy to use as Quartz. Quartz is currently the only free open source Java library for doing these types of scheduling tasks, and it really makes a great addition to a developer's bag of tricks. You can download Quartz from Open Symphony and you can find an excellent tutorial and cookbook on the same site.

Resources

Chris Hardin is a Senior Java Architect in Birmingham, Alabama.


Return to ONJava.com.