This is how I added a Quartz job to my webapp:
- Implement a simple Quartz job
- Create a configuration file that would start this job
- Create a Quarty properties file
- Add the Quartz context listener to the webapp to auto-start the scheduler
Implement a simple Quartz job (example/ExampleJob.java):
This Job just prints the value of the job parameter “message” to the console.package example;
import org.quartz.Job;
import JobExecutionContext;
public class ExampleJob implements Job {
public void execute(JobExecutionContext context) {
System.out.println(context.getJobDetail().getJobDataMap().get("message"));
}
}Create a configuration file that would start this job (resources/quartz/jobs.xml):
The job is triggered 4 times (3 repreats) in a 10 seconds interval.<?xml version="1.0" encoding="UTF-8"?>
<quartz xmlns="http://www.opensymphony.com/quartz/JobSchedulingData"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opensymphony.com/quartz/JobSchedulingData
http://www.opensymphony.com/quartz/xml/job_scheduling_data_1_5.xsd"
version="1.5">
<job>
<job-detail>
<name>ExampleJob</name>
<group>examples</group>
<job-class>example.ExampleJob</job-class>
<job-data-map>
<entry>
<key>message</key>
<value>Hello World</value>
</entry>
</job-data-map>
</job-detail>
<trigger>
<simple>
<name>ExampleTrigger</name>
<group>examples</group>
<job-name>ExampleJob</job-name>
<job-group>examples</job-group>
<repeat-count>3</repeat-count>
<repeat-interval>10000</repeat-interval>
</simple>
</trigger>
</job>
</quartz>
Create a Quarty properties file (resources/quartz/quartz.properties):# General properties:
org.quartz.scheduler.instanceName=MACHwbQuartzScheduler
org.quartz.scheduler.instanceId=AUTO
# Thread pool:
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount=1
# Load jobs from XML file:
org.quartz.plugin.jobInitializer.class=org.quartz.plugins.xml.JobInitializationPlugin
org.quartz.plugin.jobInitializer.fileName=resources/quartz/jobs.xml
org.quartz.plugin.jobInitializer.failOnFileNotFound=true
Add the Quartz context listener to the webapp to auto-start the scheduler (WEB-INF/web.xml): <web-app>
[...]
<context-param>
<param-name>config-file</param-name>
<param-value>resources/quartz/quartz.properties</param-value>
<description>Location of the Quartz configuration file</description>
</context-param>
[...]
<listener>
<listener-class>org.quartz.ee.servlet.QuartzInitializerListener</listener-class>
</listener>
[...]
</web-app>
…but it is easier with Spring.