下面我們來看一下Spring中提供的定時任務開發:在Spring中開發定時任務,分為3個步驟.
1 創建定時任務
2 註冊定時任務
3 啟動定時任務分別來看一下
1 創建定時任務:
package org.jnotnull; import java.util.TimerTask; public class MyTesk extends TimerTask{ .... public void run(){ //添加任務 } .... } |
2 註冊定時任務,並設置參數
我們來配置TimerConfig.xml防禦WEB-INF下
<bean id="myTesk" class="edu.cumt.jnotnull.action.TaskAction"> <property name="newsManageService"> <ref bean="newsManageService" /> </bean> <bean id="stTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> <property name="delay"> <value>20000</value> </property> <property name="period"> </property> <property name="timerTask"> <ref bean="myTesk" /> </property> </bean> <bean id="timerFactory" <property name="scheduledTimerTasks"> <list> <ref bean="stTask" /> </list> </property> </bean> 3 啟動定時任務 <PRE class=xml name="code"><?xml version="1.0" encoding="UTF-8"?> <context-param> <param-name>contextConfigLocation</param-name> <param-value>http://www.bt285.cn /WEB-INF/TimerConfig.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener> </web-app> </PRE> <BR> <BR>下面我們再來看看在Spring中如何使用Quartz實現定時功能 <BR>1 創建定時任務: <BR><PRE class=java name="code">package org.jnotnull; /** *http://www.5a520.cn */ public class MyTesk extends TimerTask{ public void excute(){ //添加任務 } . } </PRE> <BR>2 註冊定時任務,並設置參數 <BR>我們來配置TimerConfig.xml防禦WEB-INF下 <BR><PRE class=xml name="code"><?xml version="1.0" encoding="UTF-8"> "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id ="myTesk" class="org.jnotnull.MyTesk"/> <bean id ="myJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"> <ref bean="myTask"> </property> <propertyproperty ="targetMethod"> <value>execute</value> </property> </bean> <bean id ="timeTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail"> <ref bean="myJob"> </property> <property name="cronExpression"> <value>12,23****?</value> </property> </bean> class="org.springframework.scheduling.quartz.ScheduleFactoryBean"> <property name="triggers"> <list> <refref="timeTrigger"> </list> </property> </bean> </beans> </PRE> <BR>3 啟動定時任務 <BR><PRE class=xml name="code"><?xml version="1.0" encoding="UTF-8"?> <web-app> <context-param> <param-name>contextConfigLocation</param-name> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> </PRE> |
[火星人 ] Spring中的定時任務介紹已經有442次圍觀