Transcription

Quartz Scheduler Example Programs and Sample CodeVersion 2.2.1

This document applies to Quar Scheduler Version 2.2.1 and to all subsequent releases.Specifications contained herein are subject to change and these changes will be reported in subsequent release notes or new editions.Copyright 2010-2015 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/orits affiliates and/or their licensors.The name Software AG and all Software AG product names are either trademarks or registered trademarks of Software AG and/orSoftware AG USA Inc. and/or its subsidiaries and/or its affiliates and/or their licensors. Other company and product names mentionedherein may be trademarks of their respective owners.Detailed information on trademarks and patents owned by Software AG and/or its subsidiaries is located ath p://softwareag.com/licenses.This software may include portions of third-party products. For third-party copyright notices, license terms, additional rights orrestrictions, please refer to "License Texts, Copyright Notices and Disclaimers of Third Party Products". For certain specific third-partylicense restrictions, please refer to section E of the Legal Notices available under "License Terms and Conditions for Use of Software AGProducts / Copyright and Trademark Notices of Software AG Products". These documents are part of the product documentation, locatedat h p://softwareag.com/licenses and/or in the root installation directory of the licensed product(s).Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement withSoftware AG.Document ID: QS-EX-221-20150415

MTable of ContentsTable of ContentsThe Quartz Example Programs. 5About the Quartz Example Programs. 6Example 1 - Your First Quartz Program.7Example 3 - Cron-based Triggers. 9Example 4 - Job Parameters and Job State.11Example 5 - Job Misfires. 14Example 6 - Dealing with Job Exceptions.17Example 14 - Trigger Priorities.19Quartz Code Snippets. 23About the Code Snippets. 24How-To: Use Multiple (Non-Clustered) Schedulers.24How-To: Define a Job (with input data).25How-To: Schedule a Job. 26How-To: Unschedule a Job. 26How-To: Store a Job for Later Use. 26How-To: Schedule an Already Stored Job. 27How-To: Update an Existing Job.27How-To: Update a Trigger. 27How-To: Initialize Job Data with Scheduler Initialization. 28How-To: List Jobs in the Scheduler. 29How-To: List Triggers in Scheduler. 29How-To: Find Triggers of a Job.30How-To: Use Job Listeners. 30How-To: Use Trigger Listeners.31How-To: Use Scheduler Listeners. 32How-To: Create a Trigger that Executes Every Ten Seconds. 33How-To: Create a Trigger That Executes Every 90 minutes. 33How-To: Create a Trigger that Executes Every Day. 33How-To: Create a Trigger that Executes Every 2 Days. 34How-To: Create a Trigger that Executes Every Week.35How-To: Create a Trigger that Executes Every 2 Weeks.36How-To: Create a Trigger that Executes Every Month.37Quartz Scheduler Example Programs and Sample Code Version 2.2.13

MEven HeaderQuartz Scheduler Example Programs and Sample Code Version 2.2.14

MOdd HeaderThe Quartz Example Programs1The Quartz Example Programs About the Quartz Example Programs .6 Example 1 - Your First Quartz Program .7 Example 3 - Cron-based Triggers .9 Example 4 - Job Parameters and Job State .11 Example 5 - Job Misfires .14 Example 6 - Dealing with Job Exceptions .17 Example 14 - Trigger Priorities .19Quartz Scheduler Example Programs and Sample Code Version 2.2.15

MEven HeaderThe Quartz Example ProgramsAbout the Quartz Example ProgramsWelcome to the documentation for the Quar example programs. Quar ships with 13out-of-the-box examples that demonstrate various features of Quar and the Quar API.Where to Find the ExamplesAll of the examples listed below are part of the Quar distribution.The quar examples reside in the “examples” directory under the main Quar directory. In the examples directory, you will find a sub-directory for each example.Each sub-directory includes UNIX/Linux shell scripts for executing the examples as wellat Windows batch files. Additionally, every example has a readme.txt file. Please consultthe readme file before running the examples.The source code for the examples is located in the org.quar .examples package. You willfind a sub-package for each example.The ExamplesThe following provides an overview of the example programs. Documentation isprovided for certain examples, as noted below.Example 1 - First Quar Program: Provides a “Hello World” example for Quar . See"Example 1 - Your First Quar Program" on page 7.Example 2 - Simple Triggers: Shows a dozen different ways of using Simple Triggersto schedule your jobs.Example 3 - Cron Triggers: Shows how Cron Triggers can be used to schedule yourjob. See "Example 3 - Cron-based Triggers" on page 9.Example 4 - Job State and Parameters: Demonstrates how parameters can be passedinto jobs and how jobs maintain state. See "Example 4 - Job Parameters and Job State"on page 11.Example 5 - Handling Job Misfires: Show how to handle misfires when a job does notexecute when it is supposed to. See "Example 5 - Job Misfires" on page 14.Example 6 - Dealing with Job Exceptions: Shows how to deal with exceptions thatare thrown by your job. See "Example 6 - Dealing with Job Exceptions" on page17.Example 7 - Interrupting Jobs: Shows how the scheduler can interrupt your jobs andhow to code your jobs to deal with interruptions.Example 8 - Fun with Calendars: Demonstrates how a Holiday calendar can be usedto exclude execution of jobs on a holiday.Quartz Scheduler Example Programs and Sample Code Version 2.2.16

MOdd HeaderThe Quartz Example ProgramsExample 9 - Job Listeners: Shows how to use job listeners to have one job triggeranother job, building a simple workflow.Example 10 - Using Quar Plug-Ins: Demonstrates the use of the XML JobInitialization plug-in as well as the History Logging plug-ins.Example 11 - Quar Under High Load: Shows how to use thread pools to limit thenumber of jobs that can execute simultaneously.Example 12 - Remote Job Scheduling using RMI: Shows how to use the RemoteMethod Invocation to have Quar Scheduler remotely scheduled by a client.Example 13 - Clustered Quar : Demonstrates how Quar can be used in aclustered environment and how Quar can use the database to persist schedulinginformation.Example 14 - Trigger Priorities: Demonstrates how Trigger priorities can be used tomanage firing order for Triggers with the same fire time. See "Example 14 - TriggerPriorities" on page 19.Example 15 - TC Clustered Quar : Demonstrates how to cluster Quar using aTerraco a Server Array, rather than with a database.Example 1 - Your First Quartz ProgramThis example is designed to demonstrate how to get up and running with Quar . Thisexample will fire off a simple job that says “Hello World.”The program will perform the following actions:Start up the Quar SchedulerSchedule a job to run at the next even minuteWait for 90 seconds to give Quar a chance to run the jobShut down the schedulerRunning the ExampleThis example can be executed from the examples/example1 directory. There are twoways to run this exampleexample1.sh - A UNIX/Linux shell scriptexample1.bat - A Windows Batch fileThe CodeThe code for this example resides in the package org.quar .examples.example1.The code in this example is made up of the following classes:Quartz Scheduler Example Programs and Sample Code Version 2.2.17

MEven HeaderThe Quartz Example ProgramsClass NameDescriptionSimpleExampleThe main program.HelloJobA simple job that says Hello World.HelloJobHelloJob is a simple job that implements the Job interface and logs a message to the log(by default, this will simply go to the screen). The current date and time is printed in thejob so that you can see exactly when the job was execcuted.public void execute(JobExecutionContext context) throws JobExecutionException {// Say Hello to the World and display the date/timelog.info("Hello World! - " new Date());}SimpleExampleThe program starts by ge ing an instance of the Scheduler. This is done by creating aStdSchedulerFactory and then using it to create a scheduler. This will create a simple,RAM-based scheduler.SchedulerFactory sf new StdSchedulerFactory();Scheduler sched sf.getScheduler();HelloJob is defined as a job to Quar using the JobDetail class:// define the job and tie it to our HelloJob classJobDetail job newJob(HelloJob.class).withIdentity("job1", "group1").build();We create a SimpleTrigger that will fire off at the next round minute:// compute a time that is on the next round minuteDate runTime evenMinuteDate(new Date());// Trigger the job to run on the next round minuteTrigger trigger newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build();We now will associate the job to the trigger in the scheduler:// Tell quartz to schedule the job using our triggersched.scheduleJob(job, trigger);At this point, the job is scheduled to run when its trigger fires. However, the scheduler isnot yet running. So, we must tell the scheduler to start up.sched.start();To let the scheduler have an opportunity to run the job, our program sleeps for 90seconds. The scheduler is running in the background and should fire off the job duringthose 90 seconds.Thread.sleep(90L * 1000L);Quartz Scheduler Example Programs and Sample Code Version 2.2.18

MOdd HeaderThe Quartz Example ProgramsFinally, the program gracefully shuts down the scheduler:sched.shutdown(true);Note:Passing “true” to the shutdown method tells Quar Scheduler to wait until alljobs have completed running before returning from the method call.Example 3 - Cron-based TriggersThis example is designed to demonstrate how you can use CronTriggers to schedulejobs. This example will fire off several simple jobs that say “Hello World” and displaythe date and time that the job was executed.The program will perform the following actions:Start up the Quar SchedulerSchedule several jobs using various features of CronTriggerWait for 300 seconds (5 minutes) to give Quar a chance to run the jobsShut down the schedulerNote:Refer to the Quar Javadoc for a thorough explanation of CronTrigger.Running the ExampleThis example can be executed from the examples/example3 directory. There are twoways to run this exampleexample3.sh - A UNIX/Linux shell scriptexample3.bat - A Windows batch fileThe CodeThe code for this example resides in the package org.quar .examples.example3.The code in this example is made up of the following classes:Class NameDescriptionCronTriggerExampleThe main program.SimpleJobA simple job that says Hello World and displays the date/time.SimpleJobSimpleJob is a simple job that implements the Job interface and logs a message to the log(by default, this will simply go to the screen). The current date and time is printed in thejob so that you can see exactly when the job was executed.Quartz Scheduler Example Programs and Sample Code Version 2.2.19

MEven HeaderThe Quartz Example Programspublic void execute(JobExecutionContext context) throws JobExecutionException {JobKey jobKey b says: " jobKey " executing at " new Date());}CronTriggerExampleThe program starts by ge ing an instance of the Scheduler. This is done by creating aStdSchedulerFactory and then using it to create a scheduler. This will create a simple,RAM-based scheduler.SchedulerFactory sf new StdSchedulerFactory();Scheduler sched sf.getScheduler();Job #1 is scheduled to run every 20 secondsJobDetail job newJob(SimpleJob.class).withIdentity("job1", "group1").build();CronTrigger trigger newTrigger().withIdentity("trigger1", "group1").withSchedule(cronSchedule("0/20 * * * * ?")).build();sched.scheduleJob(job, trigger);Job #2 is scheduled to run every other minute starting at 15 seconds past the minute.job newJob(SimpleJob.class).withIdentity("job2", "group1").build();trigger newTrigger().withIdentity("trigger2", "group1").withSchedule(cronSchedule("15 0/2 * * * ?")).build();sched.scheduleJob(job, trigger);Job #3 is scheduled to run every other minute between 8am and 5pm (17 :00).job newJob(SimpleJob.class).withIdentity("job3", "group1").build();trigger newTrigger().withIdentity("trigger3", "group1").withSchedule(cronSchedule("0 0/2 8-17 * * ?")).build();sched.scheduleJob(job, trigger);Job #4 is scheduled to run every three minutes, but only between 5pm and 11pmjob newJob(SimpleJob.class).withIdentity("job4", "group1").build();trigger newTrigger().withIdentity("trigger4", "group1").withSchedule(cronSchedule("0 0/3 17-23 * * ?")).build();sched.scheduleJob(job, trigger);Job #5 is scheduled to run at 10am on the 1st and 15th days of the monthjob newJob(SimpleJob.class).withIdentity("job5", "group1").build();trigger newTrigger().withIdentity("trigger5", "group1")Quartz Scheduler Example Programs and Sample Code Version 2.2.110

MOdd HeaderThe Quartz Example Programs.withSchedule(cronSchedule("0 0 10am 1,15 * ?")).build();sched.scheduleJob(job, trigger);Job #6 is scheduled to run every 30 seconds on weekdays (Monday through Friday)job newJob(SimpleJob.class).withIdentity("job6", "group1").build();trigger newTrigger().withIdentity("trigger6", "group1").withSchedule(cronSchedule("0,30 * * ? * MON-FRI")).build();sched.scheduleJob(job, trigger);Job #7 is scheduled to run every 30 seconds on weekends (Saturday and Sunday)job newJob(SimpleJob.class).withIdentity("job7", "group1").build();trigger newTrigger().withIdentity("trigger7", "group1").withSchedule(cronSchedule("0,30 * * ? * SAT,SUN")).build();sched.scheduleJob(job, trigger);The scheduler is then started (it also would have been fine to start it before schedulingthe jobs).sched.start();To let the scheduler have an opportunity to run the job, our program sleeps for fiveminutes (300 seconds). The scheduler is running in the background and should fire offseveral jobs during that time.Note:Because many of the jobs have hourly and daily restrictions on them, not all ofthe jobs will run in this example. For example: Job #6 only runs on weekdayswhile Job #7 only runs on weekends.Thread.sleep(300L * 1000L);Finally, the program gracefully shuts down the scheduler:sched.shutdown(true);Note:Passing “true” into the shutdown() method tells the Quar Scheduler to waituntil all jobs have completed running before returning from the method call.Example 4 - Job Parameters and Job StateThis example is designed to demonstrate how you can pass run-time parameters intoQuar jobs and how you can maintain state in a job.The program will perform the following actions:Start up the Quar SchedulerSchedule two jobs, each job will execute every ten seconds for a specified total oftimesQuartz Scheduler Example Programs and Sample Code Version 2.2.111

MEven HeaderThe Quartz Example ProgramsThe scheduler will pass a run-time job parameter of “Green” to the first job instanceThe scheduler will pass a run-time job parameter of “Red” to the second job instanceThe program will wait 60 seconds so that the two jobs have plenty of time to runShut down the schedulerRunning the ExampleThis example can be executed from the examples/example4 directory. There are twoways to run this exampleexample4.sh - A UNIX/Linux shell scriptexample4.bat - A Windows Batch fileThe CodeThe code for this example resides in the package org.quar .examples.example4.The code in this example is made up of the following classes:Class NameDescriptionJobStateExampleThe main program.ColorJobA simple job that prints a favorite color (passed in as a runtime parameter) and displays its execution count.ColorJobColorJob is a simple class that implement the Job interface and is annotated as oncurrentExecutionpublic class ColorJob implements Job {The annotations cause behavior as their names describe. Multiple instances of thejob will not be allowed to run concurrently (consider a case where a job has code inits execute() method that takes 34 seconds to run, but it is scheduled with a triggerthat repeats every 30 seconds), and will have its JobDataMap contents re-persisted inthe scheduler's JobStore after each execution. For the purposes of this example, [email protected] annotation is truly relevant, but it's always wise touse the @DisallowConcurrentExecution annotation with it, to prevent race-conditionson saved data.ColorJob logs the following information when the job is executed:The job's identification key (name and group) and time/date of executionThe job's favorite color (which is passed in as a run-time parameter)Quartz Scheduler Example Programs and Sample Code Version 2.2.112

MOdd HeaderThe Quartz Example ProgramsThe job's execution count calculated from a member variableThe job's execution count maintained as a job map parameterlog.info("ColorJob: " jobKey " executing at " new Date() "\n" " favorite color is " favoriteColor "\n" " execution count (from job map) is " count "\n" " execution count (from job member variable) is " counter);The variable favoriteColor is passed in as a job parameter. It is retrieved as follows fromthe JobDataMap:JobDataMap data context.getJobDetail().getJobDataMap();String favoriteColor data.getString(FAVORITE COLOR);The variable count is stored in the job data map as well:JobDataMap data context.getJobDetail().getJobDataMap();int count data.getInt(EXECUTION COUNT);The variable is later incremented and stored back into the job data map so that job statecan be preserved:count ;data.put(EXECUTION COUNT, count);There is also a member variable named counter . This variable is defined as a membervariable to the class:private int counter 1;This variable is also incremented and displayed. However, its count will always bedisplayed as “1” because Quar will always instantiate a new instance of the classduring each execution. This prevents member variables from being used to maintainstate.JobStateExampleThe program starts by ge ing an instance of the Scheduler. This is done by creating aStdSchedulerFactory and then using it to create a scheduler. This will create a simple,RAM-based scheduler.SchedulerFactory sf new StdSchedulerFactory();Scheduler sched sf.getScheduler();Job #1 is scheduled to run every 10 seconds, for a total of five times:JobDetail job1 newJob(ColorJob.class).withIdentity("job1", "group1").build();SimpleTrigger trigger1 newTrigger().withIdentity("trigger1", (4)).build();Job #1 is passed in two job parameters. One is a favorite color, with a value of “Green”.The other is an execution count, which is initialized with a value of 1.job1.getJobDataMap().put(ColorJob.FAVORITE COLOR, ON COUNT, 1);Quartz Scheduler Example Programs and Sample Code Version 2.2.113

MEven HeaderThe Quartz Example ProgramsJob #2 is also scheduled to run every 10 seconds, for a total of five times:JobDetail job2 newJob(ColorJob.class).withIdentity("job2", "group1").build();SimpleTrigger trigger2 newTrigger().withIdentity("trigger2", (4)).build();Job #2 is also passed in two job parameters. One is a favorite color, with a value of“Red”. The other is an execution count, which is initialized with a value of 1.job2.getJobDataMap().put(ColorJob.FAVORITE COLOR, "Red");job2.getJobDataMap().put(ColorJob.EXECUTION COUNT, 1);The scheduler is then started.sched.start();To let the scheduler have an opportunity to run the job, our program will sleep for oneminute (60 seconds)Thread.sleep(60L * 1000L);Finally, the program gracefully shuts down the scheduler:sched.shutdown(true);Note:Passing “true” to the shutdown method tells Quar Scheduler to wait until alljobs have completed running before returning from the method call.Example 5 - Job MisfiresThis example is designed to demonstrate concepts related to trigger misfires.The program will perform the following actions:Start up the Quar SchedulerSchedule two jobs, each job will execute every three seconds for an indefinite lengthof timeThe jobs will take ten seconds to run (preventing the execution trigger from firingevery three seconds)Each job has different misfire instructionsThe program will wait 10 minutes so that the two jobs have plenty of time to runShut down the schedulerQuartz Scheduler Example Programs and Sample Code Version 2.2.114

MOdd HeaderThe Quartz Example ProgramsRunning the ExampleThis example can be executed from the examples/example5 directory. There are twoways to run this exampleexample5.sh - A UNIX/Linux shell scriptexample5.bat - A Windows Batch fileThe CodeThe code for this example resides in the package org.quar .examples.example5.The code in this example is made up of the following classes:Class NameDescriptionMisfireExampleThe main program.StatefulDumbJobA simple job class whose execute method takes 10 seconds torun.StatefulDumbJobStatefulDumbJob is a simple job that prints its execution time and then waits for a periodof time before completing. The amount of wait time is defined by the job parameterEXECUTION DELAY. If this job parameter is not passed in, the job will default to a waittime of 5 seconds. The job also keeps its own count of how many times it has executedusing a value in its JobDataMap called NUM EXECUTIONS. Because the class has thePersistJobDataAfterExecution annotation, the execution count is preserved betweeneach ncurrentExecutionpublic class StatefulDumbJob implements Job {public static final String NUM EXECUTIONS "NumExecutions";public static final String EXECUTION DELAY "ExecutionDelay";public StatefulDumbJob() {}public void execute(JobExecutionContext context)throws JobExecutionException {System.err.println("---" context.getJobDetail().getKey() " executing.[" new Date() "]");JobDataMap map context.getJobDetail().getJobDataMap();int executeCount 0;if (map.containsKey(NUM EXECUTIONS)) {executeCount map.getInt(NUM EXECUTIONS);}executeCount ;map.put(NUM EXECUTIONS, executeCount);long delay 5000l;if (map.containsKey(EXECUTION DELAY)) {delay map.getLong(EXECUTION DELAY);}try {Quartz Scheduler Example Programs and Sample Code Version 2.2.115

MEven HeaderThe Quartz Example Programs}}Thread.sleep(delay);} catch (Exception ignore) {}System.err.println(" -" context.getJobDetail().getKey() " complete (" executeCount ").");MisfireExampleThe program starts by ge ing an instance of the Scheduler. This is done by creating aStdSchedulerFactory and then using it to create a scheduler. This will create a simple,RAM-based scheduler, because no quar .properties telling it to do otherwise areprovided.SchedulerFactory sf new StdSchedulerFactory();Scheduler sched sf.getScheduler();Job #1 is scheduled to run every 3 seconds indefinitely. An execution delay of 10 secondsis passed into the job:JobDetail job ulJob1", "group1").usingJobData(StatefulDumbJob.EXECUTION DELAY, 10000L).build();SimpleTrigger trigger newTrigger().withIdentity("trigger1", .build();sched.scheduleJob(job, trigger);Job #2 is scheduled to run every 3 seconds indefinitely. An execution delay of 10 secondsis passed into the job:job ulJob2", "group1").usingJobData(StatefulDumbJob.EXECUTION DELAY, 10000L).build();trigger newTrigger().withIdentity("trigger2", ()) // set// misfire instruction.build();Note:The trigger for job #2 is set with a misfire instruction that will cause it toreschedule with the existing repeat count. This policy forces Quar torefire the trigger as soon as possible. Job #1 uses the default “smart” misfirepolicy for simple triggers, which causes the trigger to fire at it’s next normalexecution time.The scheduler is then started.sched.start();Quartz Scheduler Example Programs and Sample Code Version 2.2.116

MOdd HeaderThe Quartz Example ProgramsTo let the scheduler have an opportunity to run the job, our program sleeps for tenminutes (600 seconds)Thread.sleep(600L * 1000L);Finally, the program gracefully shuts down the scheduler:sched.shutdown(true);Note:Passing “true” to the shutdown method tells Quar Scheduler to wait until alljobs have completed running before returning from the method call.Example 6 - Dealing with Job ExceptionsThis example is designed to demonstrate how to deal with job execution exceptions.Jobs in Quar are permi ed to throw a JobExecutionExceptions. When this exception isthrown, you can direct Quar to take a specified action.The program will perform the following actions:Start up the Quar Scheduler.Schedule two jobs. Each job will execute every three seconds for an indefinite periodof time.The jobs will throw exceptions and Quar will take appropriate action.The program will wait 60 seconds so that the two jobs have plenty of time to run.Shut down the scheduler.Running the ExampleThis example can be executed from the examples/example6 directory. There are twoways to run this exampleexample6.sh - A UNIX/Linux shell scriptexample6.bat - A Windows Batch fileThe CodeThe code for this example resides in the package org.quar .examples.example6.The code in this example is made up of the following classes:Class NameDescriptionJobExceptionExampleThe main program.BadJob1A simple job that will throw an exception and instructQuar to refire its trigger immediately.Quartz Scheduler Example Programs and Sample Code Version 2.2.117

MEven HeaderThe Quartz Example ProgramsClass NameDescriptionBadJob2A simple job that will throw an exception and instructQuar to never schedule the job again.BadJob1BadJob1 is a simple job that creates an artificial exception (divide by zero). Whenthis exception occurs, a JobExecutionException is thrown and set to refire the jobimmediately.try {int zero 0;int calculation 4815 / zero;}catch (Exception e) {log.info("--- Error in job!");JobExecutionException e2 new JobExecutionException(e);// this job will refire immediatelye2.refireImmediately();throw e2;}This will force Quar to run this job over and over again.BadJob2BadJob2 is a simple job that creates an ar

Start up the Quar Scheduler Schedule a job to run at the next even minute Wait for 90 seconds to give Quar a chance to run the job Shut down the scheduler Running the Example This example can be executed from the examples/example1 directory. There are two ways to