用Spring framework实现定时器功能

采用Web自动加载TimerManager来管理Timer链,在Class更新服务器热加载后会发生异常。这要求对TimerManager进行一些特殊的处理才能保证Timer链的正确性。

使用Spring framework中提供的TimerTask自动加载功能可以非常容易的实现定时器链的管理。同时,采用Spring framework的这一功能可以非常容易的对定时器进行添加、删除。

1.在Web.xml中申明

  1. <context-param>  
  2. <param-name>contextConfigLocation</param-name>  
  3. <param-value>/WEB-INF/schedulingContext-timer.xml</param-value>  
  4. </context-param>  
  5. <servlet>  
  6. <servlet-name>context</servlet-name>  
  7. <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>  
  8. <load-on-startup>3</load-on-startup>  
  9. </servlet> 

2.在schedulingContext-timer.xml描述用户的定时器

  1. <bean id="timer" class="org.springframework.scheduling.timer.TimerFactoryBean">  
  2.   <property name="scheduledTimerTasks">  
  3.   <list>  
  4.   <ref local="JorwangScheduledTimerTask1"/>  
  5. feedom.net  
  6.   </list>  
  7.   </property>  
  8.   </bean>  
  9.   <bean id="JorTimeTask1" class="workflow.common.MyTimer">  
  10.   </bean>  
  11.   <bean id="JorwangScheduledTimerTask1" class="org.springframework.scheduling.timer.ScheduledTimerTask">  
  12.   <property name="timerTask"><ref bean="JorTimeTask1"/></property>  
  13.   <property name="delay"><value>10000</value></property>  
  14.   <property name="period"><value>86400000</value></property>  
  15.   </bean> 

3.编写workflow.common.MyTimer定时器

这样就轻松用Spring framework完成了定时器的功能。如果需要修改、增加、删除定时器,只需要对2、3步的内容进行调整就可以实现。

【编辑推荐】

  1. Spring Module 0.3版本发布
  2. 在Spring中XFire构建Web Service
  3. Spring Web Services框架入门研究
  4. Sun GlassFish对Spring的支持
  5. 详细介绍Spring的核心
THE END