spring配置quartz定時任務,支援初始化執行,迴圈執行,定點執行等
阿新 • • 發佈:2018-12-21
Spring配置quartz的方式有註解的方式和配置檔案的方式,今天主要說使用配置檔案的方式來實現初始化執行和定點執行
第一步,在pom.xml配置jar包依賴
<!-- 新加quartz依賴 --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.1</version> </dependency>
第二步,建立spring-quartz.xml配置檔案
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" default-lazy-init="false"> <!--需要執行的任務類--> <bean id="quartzJob" class="com.zit.korla.basestation.quartz.SynSectionInfoJob" /> <!-- 需要執行的任務 --> <bean id="jobDetail_1" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"> <ref bean="quartzJob" /> </property> <property name="targetMethod"> <value>work</value> </property> </bean> <!-- 配置指定的時間執行一次任務,可以指定在某個點執行任務 --> <bean id="cronTriggerBeanTest" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="jobDetail_1" /> <property name="cronExpression"> <value>0 0 0 * * ?</value> </property> </bean> <!-- 配置間隔多長時間執行一次任務,name=repeatInterval value="3000"就是每隔3秒鐘執行一次 ,value=0,表示立即執行--> <bean id="simpleTriggerBeanTest" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"> <property name="jobDetail" ref="jobDetail_1" /> <property name="startDelay" value="500" /> <property name="repeatInterval" value="0" /> <property name="repeatCount" value="0" /> </bean> <!--開始執行上面的兩個定時任務--> <bean id="startQuertz" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="simpleTriggerBeanTest" /> <ref bean="cronTriggerBeanTest" /> </list> </property> </bean> </beans>
第三步:編寫上面的幹活的類SynSectionInfoJob
public class SynSectionInfoJob {
public void work()
{
System.out.println("載入完成了");
}
}
第四步:可以在web.xml、springmvc.xml或者spring.xml三個配置檔案中都可以引入spring-quartz.xml
<!--在springmvc.xml或spring.xml這樣引入--> <import resource="classpath:spring-quartz.xml"/>
<!--在web.xml中這樣引入-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml,classpath:spring-quartz.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
啟動工程,系統啟動後可以列印“載入完成了”