Scheduling with Quartz
Batch solutions are ideal for processing that is time and/or state based:
- Time-based: The business function executes on a recurring basis, running at pre-determined schedules.
- State-based: The jobs will be run when the system reaches a specific state.
- Can run embedded within another free standing application
- Can be instantiated within an application server (or servlet container).
- Can participate in XA transactions, via the use of JobStoreCMT.
- Can run as a stand-alone program (within its own Java Virtual Machine), to be used via RMI
- Can be instantiated as a cluster of stand-alone programs (with load-balance and fail-over capabilities)
- Supoprt for Fail-over
- Support for Load balancing.
- Download the latest version of quartz from opensymphony.
- Make sure you have the following in your class path (project-properties->java build path):
- The quartz jar file (quartz-1.6.0.jar).
- Commons logging (commons-logging-1.0.4.jar)
- Commons Collections (commons-collections-3.1.jar)
- Add any server runtime to your classpath in eclipse. This is for including the Java transaction API used by Quartz. Alternatively, you can include the JTA class files in your classpath as follows
- Download the JTA classes zip file from the JTA download page.
- Extract the files in the zip file to a subdirectory of your project in Eclipse.
- Add the directory to your Java Build Path in the project->preferences, as a class directory.
- Implement a Quartz Job: A quartz job is the task that will run at the scheduled time.
public class SimpleJob implements Job {
public void execute(JobExecutionContext ctx) throws JobExecutionException {
System.out.println("Executing at: " + Calendar.getInstance().getTime() + " triggered by: " + ctx.getTrigger().getName());
}
} - The following piece of code can be used to run the job using a scheduler.
public class QuartzTest {
public static void main(String[] args) {
try {
// Get a scheduler instance.
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
long ctime = System.currentTimeMillis();
// Create a trigger.
JobDetail jobDetail = new JobDetail("Job Detail", "jGroup", SimpleJob.class);
SimpleTrigger simpleTrigger = new SimpleTrigger("My Trigger", "tGroup");
simpleTrigger.setStartTime(new Date(ctime));
// Set the time interval and number of repeats.
simpleTrigger.setRepeatInterval(100);
simpleTrigger.setRepeatCount(10);
// Add trigger and job to Scheduler.
scheduler.scheduleJob(jobDetail, simpleTrigger);
// Start the job.
scheduler.start();
} catch (SchedulerException ex) {
ex.printStackTrace();
}
}
}
A trigger is used to define the schedule in which to run the job.