Use Quartz to schedule tasks in Spring
Friday, May 7th, 2010
Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java EE or Java SE application.
In this simple example (notionally checking Twitter for updates) we integrate it with Spring.
Spring Config
<bean name="checkTwitterForUpdates" class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass" value="test.twitterReader" /> </bean> <bean id="cronTwitterUpdateCheckTriggerBean" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="checkTwitterForUpdates" /> <!-- Run every day at noon --> <property name="cronExpression" value="0 0 12 * * ?" /> </bean> <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cronTwitterUpdateCheckTriggerBean" /> </list> </property> </bean>
You may just want to call a method on an existing object (perhaps a business object). We can use MethodInvokingJobDetailFactoryBean to do just this:
Often you just need to invoke a method on a specific object. Using the MethodInvokingJobDetailFactoryBean you can do exactly this:
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="someBusinessObject"/> <property name="targetMethod" value="someMethod"/> </bean>
Java
package twitter; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; public class twitterReader extends QuartzJobBean { protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException { // Like whatever....... } }
Libraries
You can get get Quartz here
You may also need:
Simple Logging Facade for Java (SLF4J) and
You can leave a response, or trackback from your own site.
Tags: java, quartz, spring
Posted in: Development, How to's