利用spring实现定时器的开发过程包括以下三个步骤:
(1)创建定时任务类.
(2)注册定时任务类,并配置任务计划和任务调度器.
(3)在WEB项目中启动定时服务.
------------------------------------------------------------------------------------------------------------
例子(定时任务类)
package dgut.ke.timer;
import java.util.TimerTask;
public class MainTask extends TimerTask {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("--------------执行定时任务---------------");
}
}
------------------------------------------------------------------------------------------------------------
文件/WEB-INF/TimerConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
<beans>
<!-- 注册定时执行实体 -->
<bean id="mainTask" class="dgut.ke.timer.MainTask"></bean>
<!-- 注册定时信息 -->
<bean id="stTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<!-- 首次执行任务前需要等待2秒钟 -->
<property name="delay">
<value>2000</value>
</property>
<!-- 任务执行的周期 -->
<property name="period">
<value>4000</value>
</property>
<!-- 具体的执行任务 -->
<property name="timerTask">
<ref local="mainTask"/>
</property>
</bean>
<!-- 配置任务调度器 -->
<bean id="timeFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
<!-- 注入定时器列表 -->
<property name="scheduledTimerTasks">
<list>
<ref local="stTask"/>
</list>
</property>
</bean>
</beans>
------------------------------------------------------------------------------------------------------------
文件web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="
http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- 启动定时服务 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/TimerConfig.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
posted on 2007-08-19 20:11
Ke 阅读(489)
评论(0) 编辑 收藏 所属分类:
spring