Posted on 2008-02-16 04:04
leekiang 阅读(971)
评论(0) 编辑 收藏 所属分类:
java
通过监听器(Listener)和定时器(Timer)定时执行某个任务(Task)。
(1)Listener
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 ); // milliseconds
}
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
}
}
(2)Task
import java.util.TimerTask;
public class MyTask extends TimerTask {
public void run() {
System.out.println(( new Date()));
}
}
(3)web.xml配置
< listener >
< listener - class > com.fastunit.samples.listener.MyListener </ listener - class >
</ listener >