Quartz is an open source for job scheduling wich may be easily plugged in any working java project.
- Step 1
In the applicationContext.xml, add the job details (class and target method). Target method should be a public method without parameters.
<bean name="aBackgroundJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" class="net.slm.BackgroundWorkerClass"/> <property name="targetMethod" value="methodToCallOnQuartzEvent"/> <!-- This job maybe concurrent (default) or exclusive --> <property name="concurrent" value="false"/> </bean>
- Step 2
Now, there are two ways to run this job using Quartz library, either a simple cron scheduled after server start and having a repeat interval (simpleTrigger) :
<bean id="dailyCronTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail" ref="aBackgroundJob"/> <!-- 2 minutes after server starting --> <property name="startDelay" value="120000"/> <!-- repeat every 24 hours (1000*60*60*24)--> <property name="repeatInterval" value="86400000"/> </bean>
The second option is to use quartz specific regular expressions to schedule fire time. Those regular expressions are explained in details here.
<bean id="dailyCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="aBackgroundJob"/> <!-- run every day at 9:30 AM --> <property name="cronExpression" value="0 30 9 * * ?"/> <property name="concurrent" value="false"/> </bean>
- Step 3
To get those events fired, you must subscribe crons to a schedular:
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="dailyCronTrigger" /> </list> </property> </bean>
-
Step 4
Some java code for the job.
package net.slm; import java.util.Date; public class BackgroundWorkerClass { public void methodToCallOnQuartzEvent(){ System.out.println("Quartz job started at "+new Date()); //or do whatever you want } }
There are similar libraries here but I think that quartz is the richest.