Posted on 2009-12-13 22:41
Gavin.lee 阅读(1056)
评论(0) 编辑 收藏 所属分类:
SSH2 --Spring
在web方式下,如果我们要实现定期执行某些任务的话,除了用quartz等第三方开源工具外,我们可以使用Timer和TimeTask来完成指定的定时任务。专业的开源工具可参考Quartz:http://www.opensymphony.com/quartz/
第一步:创建一个任务具体操作类,实现ServletContextListener 接口 MyListener.java
package yixun.wap.tools;

import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyListener implements ServletContextListener
{
private Timer timer = null;

public void contextInitialized(ServletContextEvent event)
{
timer = new Timer(true);//true 指定为后台线程
// 设置任务计划,启动和间隔时间
timer.schedule(new MyTask(), 0, 86400000);
//可写多个定时任务
}


public void contextDestroyed(ServletContextEvent event)
{
timer.cancel();
}

}
还有好几种任务调度
timer.schedule(task, time);
// time为Date类型:在指定时间执行一次。
timer.schedule(task, firstTime, period);
// firstTime为Date类型,period为long
// 从firstTime时刻开始,每隔period毫秒执行一次。
timer.schedule(task, delay)
// delay 为long类型:从现在起过delay毫秒执行一次
timer.schedule(task, delay, period)
// delay为long,period为long:从现在起过delay毫秒以后,每隔period
// 毫秒执行一次。
第二步:创建一个时间任务类 MyTask.java
package yixun.wap.tools;

import java.util.TimerTask;


public class MyTask extends TimerTask
{


public void run()
{
// System.out.println("call at " + (new Date()));
// TODO 此处添加具体任务代码
}

}
第三步:在web.xml中添加一个监听器
<listener>

<listener-class>
yixun.wap.tools.MyListener
</listener-class>
<description>要定期执行的任务</description>
</listener>

通过配置监听器,那么在web服务器启动的时候,任务也被启动,并且会周期性的执行
参考文章:http://www.blogjava.net/fastunit/archive/2008/02/15/180116.html