Friday, January 20, 2006

Using Quartz job scheduler with Spring

Quartz is an open source job scheduling system that can be integrated with, or used along side virtually any J2EE or J2SE application. Quartz can be used to trigger jobs at a specific date and time, at regular intervals, or other very complex schedules.

Although Quartz can be used in a standalone system, this article focuses on using Quartz in a J2EE application built with the Spring framework. The Spring framework has built-in support for Quartz. All you have to do is put the Quartz runtime (quartz-1.x.x.jar) in your classpath, implement the business logic to be triggered, and put some entries in your Spring configuration file.

First you have to configure a scheduler with a list of triggers.

<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
  <list>
    <ref local="reportTrigger"/>
  </list>
</property>
</bean>

Then you configure the managed beans that you want to trigger. In this case, my business logic is implemented as a stateless session bean.

<bean id="mondayMorningReport"
class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean">
<property name="jndiName"><value>ejb/mondayMorningReport</value></property>
<property name="resourceRef"><value>true</value></property>
<property name="businessInterface">
<value>com.mycompany.Report</value></property>
</bean>

Finally you configure the trigger to fires at a specific time. In my case I want a report to execute every Monday morning at 6.30 am. I use the CronTriggerBean for this purpose.

<bean id="reportTrigger"
class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
  <bean
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    <property name="targetObject"><ref bean="mondayMorningReport"/></property>
    <property name="targetMethod"><value>printReport</value></property>
  </bean>
</property>
<property name="cronExpression"><value>0 30 6 * * MON</value></property>
</bean>

A "Cron-Expression" is a string comprised of 6 or 7 fields separated by white space. The 6 mandatory and 1 optional fields are as follows:

Field Name Allowed Values Allowed Special Characters
Seconds 0-59 , - * /
Minutes 0-59 , - * /
Hours 0-23 , - * /
Day-of-month 1-31 , - * ? / L W C
Month 1-12 or JAN-DEC , - * /
Day-of-Week 1-7 or SUN-SAT , - * ? / L C #
Year (Optional) empty, 1970-2099 , - * /

The Quartz plumbing code is included in Spring 1.0 and above but you must also download the Quarts distribution and include its jar in your application. As of this writing, I use quartz-1.5.1.jar in my application.

Resources