Creating a Fire-Now Trigger

Sometimes you need to execute a job immediately. For example, imagine that you're building a GUI that allows users to execute jobs right away. As another example, you might have detected that a job didn't complete successfully, so you want to rerun the job immediately. In Quartz 1.5, several methods were added to the triggerUtils class to make that easier. Listing 5.4 shows how to schedule a job to run only once, right away.

Listing 5.4. You Can Use the TRiggerUtils to Execute an Immediate Job

public class Listing_5_4 { static Log logger = LogFactory.getLog(Listing_5_4.class); public static void main(String[] args) { Listing_5_4 example = new Listing_5_4(); 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 trigger that fires once right away Trigger trigger = TriggerUtils.makeImmediateTrigger(0, 0); trigger.setName("FireOnceNowTrigger"); scheduler.scheduleJob(jobDetail, trigger); } catch (SchedulerException ex) { logger.error(ex); } } }

In Listing 5.4, the makeImmediateTrigger() method of triggerUtils is used to execute an immediate job. The first parameter is the number of times the trigger will fire. The second parameter is the interval between the executions. The method signature is shown here for convenience:

public static Trigger makeImmediateTrigger(int repeatCount, long repeatInterval);

The TRiggerUtils class offers many convenience methods for simplifying the use of triggers. Be sure to check this utility class first to see if it has what you need. You'll see more examples of the triggerUtils class throughout the book.

Категории