定时器
程序员文章站
2023-12-21 21:53:16
...
代码:
web.xml->
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class TimeJobDemo implements ServletContextListener{
Timer timer;
public void contextDestroyed(ServletContextEvent arg0) {
timer.cancel();
System.out.println("定时器关闭");
}
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("定时器启动");
timer=new Timer();
timer.schedule(new Task(),5000,20*1000);//服务启动5秒后,每隔二十秒执行一次
System.out.println("----XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
}
}
class Task extends TimerTask{
private static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
@Override
public void run() {
System.out.println("开始执行任务:"+sdf.format(new java.util.Date()));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行任务。。。。。。。");
System.out.println("执行任务结束:"+sdf.format(new java.util.Date()));
}
}
web.xml->
<listener>
<listener-class>TimeJobDemo</listener-class>
</listener>