Thursday, January 24, 2008

Add a quartz job to Spring


There are a few steps to adding a quartz job to a Spring app:

1. Add the jars: quartz-1.6.0.jar, commons-logging.jar, commons-collections.jar. If also found I needed jta.jar for my cron trigger job.

2. Create your job class which is a QuartzJobBean, implementing the executeInternal method:

public class MyJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {

System.out.println("my job is running");
}
}

3. Add the quartz config into the spring web context xml. There are three parts:

3a. Add the job bean:

<bean name="myJob"
class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.test.MyJob" />
</bean>

3b. Add the trigger - I'm using a cron trigger which will run this job every 15 seconds:

<bean name="myTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="myJob"/>
</property>
<property name="cronExpression">
<value>0/15 * * * * ?</value>
</property>
</bean>

3c. Add the quartz factory, and name the trigger:

<bean
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="myTrigger"/>
</list>
</property>
</bean>

Compile. deploy and run!

If you want to add Spring injected classes into your job, use the jobDataAsMap property. In the example below myBean and myString have getters and setters in the MyJob class.

<bean name="myJob"
class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.test.MyJob" />
<property name="jobDataAsMap">
<map>
<entry key="myBean" value-ref="beanName" />
<entry key="myString" value="some value" />
</map>
</property>
</bean>

That's it!

No comments: