It seems today every application needs background jobs, here we are going to learn how to integrate Quartz Scheduler with Spring.
Version we are using
Spring 3.x
Quartz 1.8.6
Maven 3
we have to follow few steps for configure quartz with spring
1. Add maven depandancy in pom.xml
<!-- Quartz framework dependencies -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>1.8.6</version>
</dependency>
2..configure spring-quartz.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="jobs" class="com.yourpackage.Jobs" />
<!-- jobs define here -->
<bean id="wallFeedJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="jobs" />
<property name="targetMethod" value="wallFeed" />
</bean>
<!-- cron trigger define here -->
<bean id="cronTriggerForWall" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="wallFeedJob"/>
<property name="cronExpression" value="0 7 12 * * ?"/>
</bean>
<!-- scheduler factory bean to bind,the executing code and time intervals together -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="wallFeedJob" />
</list>
</property>
<property name="triggers">
<list>
<ref bean="cronTriggerForWall"/>
</list>
</property>
</bean>
</beans>
3.Write java classes for binds with quartz configuration
public class Jobs {
static final Logger logger = LoggerFactory.getLogger("debugLogger");
public void wallFeed()
{
logger.debug("wallFeed :::: "+Calendar.getInstance().getTime());
} }
4.For testing you can write your main class
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {public static void main(String[] args) throws Exception {
new ClassPathXmlApplicationContext("spring-quartz.xml");
}
}
- Run code and get the output
You can visit the following website for adjustment of time and date of job
http://quartz-scheduler.org/documentation/quartz-2.x/tutorials/tutorial-lesson-06
http://quartz-scheduler.org/api/2.0.0/org/quartz/CronExpression.html
May be it would help.
0 Comment(s)