Quartz Scheduler with Spring 3:
For achieving scheduled task in spring 3 with the help of Quartz, we need following jars :
Spring 3.0
Quartz 1.8.6
Step 1:
First, add defines quartz details in context file of spring i.e. spring-context.xml as shown below:
<bean id="jobA" class="com.rockmesolid.jobs.JobA" /> <!-- Quartz Job --> <bean name="JobA" class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass" value="com.rockmesolid.jobs.JobA" /> </bean> <!-- Cron Trigger, run every 5 seconds --> <bean id="cronTriggerJobA" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="JobA" /> <property name="cronExpression" value="0/5 * * * * ?" /> </bean> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cronTriggerJobA" /> </list> </property> </bean>
As you can see
<bean name=”JobA” class=”org.springframework.scheduling.quartz.JobDetailBean”>
Next step is to set CronTriggerBean which has property of cronExpression
<property name=”cronExpression” value=”0/5 * * * * ?” />
Here “0/5 * * * * ?” defines CronTrigger will hit JobA class at every 5 Second.
If you want to hit it at a particular time on everyday like 10:13 pm everyday then cronExpression would be like “*10 13 * ? *”
<bean class=”org.springframework.scheduling.quartz.SchedulerFactoryBean”>
Step 2:
Now definition of JobA is:
package com.rockmesolid.jobs;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
public class JobA extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); // for calling or inject bean of current context of application
System.out.println("Job A is runing");
try {
// to perform some actions
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here as we can see JobA extends QuartzJobBean for calling executeInternal method which passes JobExecutionContext as an argument.
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); is the most important line to call or inject bean of current context of application into the JobA class. After this line you can use any of your application bean class into JobA class and perform any action like business logic, db connection etc.
Hope it will help. Really it’s easy.
No comments:
Post a Comment