本例依据Java自身提供的接口实现,通过监听器(Listener)和定时器(Timer)定时执行某个任务(Task)。
专业的开源工具可参考Quartz: http://www.opensymphony.com/quartz/
MyListener:
MyTask:
web.xml配置:
专业的开源工具可参考Quartz: http://www.opensymphony.com/quartz/
MyListener:
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 );
// 设置任务计划,启动和间隔时间
timer.schedule( new MyTask(), 0 , 86400000 );
}
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
}
}
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 );
// 设置任务计划,启动和间隔时间
timer.schedule( new MyTask(), 0 , 86400000 );
}
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
}
}
MyTask:
import
java.util.TimerTask;
public class MyTask extends TimerTask {
public void run() {
// System.out.println("call at " + (new Date()));
// TODO 此处添加具体任务代码
}
}
public class MyTask extends TimerTask {
public void run() {
// System.out.println("call at " + (new Date()));
// TODO 此处添加具体任务代码
}
}
web.xml配置:
<
listener
>
< listener-class > com.fastunit.samples.listener.MyListener </ listener-class >
</ listener >
< listener-class > com.fastunit.samples.listener.MyListener </ listener-class >
</ listener >
源博客:http://www.blogjava.net/fastunit/archive/2008/02/15/180116.html