通过监听器(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();
}
}
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()));
}
}
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 >
< listener - class > com.fastunit.samples.listener.MyListener </ listener - class >
</ listener >