Some applications need some sort of background processes that support some aspect of a business process. This article demonstrates how to use Quartz in a simple Java application.
Software Environment
- Windows 7 Professional SP1
- Eclipse – Kepler Release
- Java 1.7 (1.7.0_67 – Windows x86)
- Quartz 2.2.1
- Reference these jar files
- quartz-2.2.1.jar
- quartz-jobs-2.2.1.jar
- Reference these jar files
- Log4j
- Reference this jar file
- log4j-1.2.16.jar
- Reference this jar file
- SLF4J 1.6.6
- Reference these jar files
- slf4j-api-1.6.6.jar
- slf4j-log4j12-1.6.6.jar
- Reference these jar files
Your log4j.xml
Yet again, log4j.xml appears. You may use your own configuration or use the file on How to configure Log4j to log to the console. As usual, make this file available in the classpath.
Java Codes
We have two classes. The MainClass starts up the scheduler, and HelloWorldJob is the task we want to execute repeatedly at an interval.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | package com.turreta.quartz; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; import static org.quartz.JobBuilder.*; import static org.quartz.TriggerBuilder.*; import static org.quartz.SimpleScheduleBuilder.*; public class MainClass { public static void main(String[] args) { try { Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.start(); JobDetail job = newJob(HelloWorldJob.class).withIdentity("job1", "group1").build(); // Repeat job every 10 seconds Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startNow() .withSchedule(simpleSchedule().withIntervalInSeconds(10).repeatForever()).build(); scheduler.scheduleJob(job, trigger); // Do not shutdown yet // scheduler.shutdown(); } catch (SchedulerException se) { se.printStackTrace(); } } } package com.turreta.quartz; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class HelloWorldJob implements Job { public void exe cute(JobExecutionContext arg0) throws JobExecutionException { System.out.println("Hello World! "); } } |
Sample Output
Download the Project
https://www.dropbox.com/s/wo2ov9yjrnjef17/QuartzAppTurretaDotCom.zip?dl=0