Friday, October 22, 2010

Java Scheduling with Quartz and Spring - Triggers

hi all, so lets do a dive into the Triggers !

As you know that a Job in a Quartz is an entity which does the work and is kept separate from when this job should be run. For executing the job at a particular time they have the concepts of a Trigger. We associate a job with a trigger, although we can associate multiple triggers with a job, i.e. we can have trigger which says "Fire this job at 9AM daily" then we can also have a trigger2 which says "Fire this job at 10AM", So the job will be fired at 9AM and 10 AM both. Why would you want this, there are times were you scheduling can become a little complex the best solution for that would be to divide the schedule in multiple points and run(There is a certain amount of complex schedule that a Trigger can accept, more on that later).
Enough theory lets code !

First as always we need the Spring configuration which can define the time when i want my job to run.


<bean id="updateFooMap" class="org.springframework.scheduling.quartz.CronTriggerBean">
     <property name="jobDetail" ref="createMapJob" />
     <property name="jobName" value="updateMap"></property>
     <property name="startDelay" value="10000" />
     <property name="cronExpression" value="0/10 * 9-17 ? * MON-FRI"></property>
</bean>

You guessed it right, we need to define a Bean! (then again ain't all object Bean ? :) ). We create this bean of type CronTriggerBean which is a wrapper class in Spring for CronTrigger class in Quartz. Give it a reference to the Job on which it should run (remember that trigger should know which job it should fire, but job should not know which trigger is working on it). We also give this trigger a name "updateJob". I also give it a start delay of 10sec after which this job would start looking whether it should fire or not. Now i have added a CronExpression which will define when this job should be run, this is no different then cron expression in Linux. I have selected the configuration to run this job after every 10 sec from 9 hrs to 1700 hrs though Monday to Friday.
Once we are ready with the Trigger Bean we need to register all the trigger beans with the Scheduling Factory in Quartz which will fire the jobs using these triggers.


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


Once this is done now we are ready with our job being run. run the application(Web or stand alone Spring application) and you should see the effects :) .

No comments: