1.在pom.xml里引入quartz.jar
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
2.创建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.2.xsd"
default-autowire="byName">
<bean id="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobFactory">
<bean class="org.springframework.scheduling.quartz.SpringBeanJobFactory" />
</property>
<property name="triggers">
<list>
<ref bean="myTrigger" />
</list>
</property>
</bean>
<bean id="myTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="cronExpression" value="0/5 * * * * ?" /> //时间格式: 秒 分 时 日 月 年
<property name="jobDetail" ref="myTriggerDetail" />
</bean>
<bean id="myTriggerDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="myTriggerJob" /> //job的执行类
<property name="targetMethod" value="execute" /> //job的执行方法
<property name="concurrent" value="false" />
</bean>
<bean id="myTriggerJob" class="com.moin.web.service.job.MyTriggerJob" />
</beans>
注:SchedulerFactoryBean的数据源属性叫datasource, 所以应该避免spring配置的数据源叫datasource。
3. 在contextConfigLocation定义的spring-context.xml配置文件里引入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.2.xsd"
default-autowire="byName">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:dbcp-config.properties" />
</bean>
<import resource="spring-datasource-jdbc.xml" />
<import resource="spring-dao.xml" />
<import resource="spring-service.xml" />
<import resource="spring-quartz.xml" />
</beans>
4, 执行job的类:MyTriggerJob:
public class MyTriggerJob {
public void execute() {
//todo something...
}
}