spring的定时启动

作者在 2011-04-21 10:16:15 发布以下内容

1)java.util.Timer   
  常用的对象和方法,但是需要手工启动任务:   
Timer timer=new Timer();   
timer.schedule(new MyTimerTask(),10000,86400000);   //10000表示延迟10000毫秒后开始执行MyTimeTask的run方法,86400000表示每隔这么久运行一次。
这里的MyTimerTask类必须继承TimerTask里面的run()方法:

public class MyTimeTask extends TimerTask {
    public void run() {
        System.out.println("This is MyTimeTask!");
    }
}

需要注意的是Timer与TimerTask是独立的两个物件,当使用Timer的schedule()方法排定TimerTask之后,则必须等执行Timer的 cancel方法执行之后,让TimerTask与Timer脱离关系,TimerTask才可以重新加入其它Timer的排程。

2)ServletContextListener   
这个方法在web容器环境比较方便,这样,在web server启动后就可以自动运行该任务,不需要手工启动。   
将MyListener implements ServletContextListener接口,在contextInitialized方法中加入启动Timer的代码,在contextDestroyed方法中加入cancel该Timer的代码;然后在web.xml中,加入listener:   
<listener>   
<listener-class>com.sysnet.demo.util.MyTimerTask</listener-class>   
</listener>   
那么web.xml文件加载后就会调用MyListener的contextInitialized方法。

3)org.springframework.scheduling.timer.ScheduledTimerTask   
如果用spring,就不需要写Timer类了,在schedulingContext-timer.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="timer" class="org.springframework.scheduling.timer.TimerFactoryBean">   
<property name="scheduledTimerTasks">   
<list>   
<ref local="MyTimeTask1"/>   
</list>   
</property>   
</bean>   
<bean id="MyTimeTask" class="com.timer.MyTimerTask"/>   
<bean id="MyTimeTask1" class="org.springframework.scheduling.timer.ScheduledTimerTask">   
<property name="timerTask">   
<ref bean="MyTimeTask"/>   
</property>   
<property name="delay">   
<value>10000</value>   
</property>   
<property name="period">   
<value>86400000</value>   
</property>   
</bean>   
</beans>   

专业文章 | 阅读 969 次
文章评论,共0条
游客请输入验证码
浏览275777次