spring中定时器的使用

 

在很多实际的web应用中,都有需要定时实现的服务,如每天12点推送个新闻,每隔一个小时提醒用户休息一下眼睛,隔一段时间检测用户是否离线等等。

spring框架提供了对定时器的支持,通过配置文件就可以很好的实现定时器,只需要应用启动,就自动启动定时器。下面介绍一下具体做法。

第一种,使用XML配置的方法

前期工作,配置spring的开发环境(这里用到了spring的web应用包,需要导入)

首先创建定时器的任务类,定时器要做什么工作,就在这里写什么方法。

  1. <span style="font-size: 18px;">package org.time;  

  2. import java.util.TimerTask;  

  3. publicclass MainTask extends TimerTask{  

  4. @Override

  5. publicvoid run() {  

  6.         System.out.println("检测用户是否掉线");  

  7.     }  

  8. }  

  9. </span>  


接着在配置文件中对定时器进行配置。

 

  1. <spanstyle="font-size: 18px;"><?xmlversion="1.0"encoding="UTF-8"?>

  2. <beans

  3. xmlns="http://www.springframework.org/schema/beans"

  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  5. xmlns:p="http://www.springframework.org/schema/p"

  6. xsi:schemaLocation="http://www.springframework.org/schema/beans   

  7.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  8. <beanid="mainTask"class="org.time.MainTask"></bean>

  9. <!-- 注册定时器信息 -->

  10. <beanid="springTask"class="org.springframework.scheduling.timer.ScheduledTimerTask">

  11. <!-- 延迟1秒执行首次任务 -->

  12. <propertyname="delay"value="1000"></property>

  13. <!-- 每隔2秒执行一次任务 -->

  14. <propertyname="period"value="2000"></property>

  15. <!-- 具体执行的任务 -->

  16. <propertyname="timerTask"ref="mainTask"></property>

  17. </bean>

  18. <!-- 配置任务调度器工厂 -->

  19. <beanid="timerFactory"class="org.springframework.scheduling.timer.TimerFactoryBean">

  20. <propertyname="scheduledTimerTasks">

  21. <list>

  22. <refbean="springTask"/>

  23. </list>

  24. </property>

  25. </bean>

  26. </beans></span>


最后还需要在web.xml中对配置信息进行注册:

 

  1. <spanstyle="font-size: 18px;"><?xmlversion="1.0"encoding="UTF-8"?>

  2. <web-appversion="2.5"

  3. xmlns="http://java.sun.com/xml/ns/javaee"

  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   

  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  7. <display-name></display-name>

  8. <welcome-file-list>

  9. <welcome-file>index.jsp</welcome-file>

  10. </welcome-file-list>

  11. <listener>

  12. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  13. </listener>

  14. <context-param>

  15. <param-name>contextConfigLocation</

    关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信