用Spring framework實(shí)現(xiàn)定時(shí)器功能
采用Web自動加載TimerManager來管理Timer鏈,在Class更新服務(wù)器熱加載后會發(fā)生異常。這要求對TimerManager進(jìn)行一些特殊的處理才能保證Timer鏈的正確性。
使用Spring framework中提供的TimerTask自動加載功能可以非常容易的實(shí)現(xiàn)定時(shí)器鏈的管理。同時(shí),采用Spring framework的這一功能可以非常容易的對定時(shí)器進(jìn)行添加、刪除。
1.在Web.xml中申明
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/schedulingContext-timer.xml</param-value>
- </context-param>
- <servlet>
- <servlet-name>context</servlet-name>
- <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
- <load-on-startup>3</load-on-startup>
- </servlet>
2.在schedulingContext-timer.xml描述用戶的定時(shí)器
- <bean id="timer" class="org.springframework.scheduling.timer.TimerFactoryBean">
- <property name="scheduledTimerTasks">
- ?。糽ist>
- ?。紃ef local="JorwangScheduledTimerTask1"/>
- feedom.net
- </list>
- ?。?property>
- ?。?bean>
- <bean id="JorTimeTask1" class="workflow.common.MyTimer">
- ?。?bean>
- ?。糱ean id="JorwangScheduledTimerTask1" class="org.springframework.scheduling.timer.ScheduledTimerTask">
- ?。紁roperty name="timerTask"><ref bean="JorTimeTask1"/></property>
- ?。紁roperty name="delay"><value>10000</value></property>
- <property name="period"><value>86400000</value></property>
- ?。?bean>
3.編寫workflow.common.MyTimer定時(shí)器
這樣就輕松用Spring framework完成了定時(shí)器的功能。如果需要修改、增加、刪除定時(shí)器,只需要對2、3步的內(nèi)容進(jìn)行調(diào)整就可以實(shí)現(xiàn)。
【編輯推薦】