Java定时任务的实现
本例依据Java自身提供的接口实现,通过监听器(Listener)和定时器(Timer)定时执行某个任务(Task)。
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);//?milliseconds
??}
??public?void?contextDestroyed(ServletContextEvent?event)?{
????timer.cancel();
??}
??
}
?
MyTask:
web.xml配置: