定时器
步骤
1. 导入定时器需要的jar包:
2.写一个类,继承TimerTask类,重写其run()方法;
3.在run()方法里写需要定时执行的任务;
4.写一个类管理定时器任务,实现ServletContextListener接口;
5.重写contextInitialized方法,在此方法里创建Timer对象,调用Timer的schedule()方法执行定时器任务;
6.在web.xml文件里配置管理定时器任务的类的路径;
示例如下:
importjava.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
publicclass MyTest1extends TimerTask{
privateSimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
@Override
public void run() {
System.out.println("现在时间是:"+sf.format(new Date()));
}
}
第二步:编写一个类,该类实现ServletContextListener接口
importjavax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
publicclass TimerTaskManagerimplements ServletContextListener{
private Timer timer;
@Override
public void contextInitialized(ServletContextEventsce) {
System.out.println("程序定时执行任务.....................................");
MyTest1 t=new MyTest1();
timer=newTimer("开始执行任务",true);//
timer.schedule(t,0,1000);//执行MyTest1中的run方法,t代表TimerTask的子类,0代表延迟0毫秒执行run方法,1000表示每隔一秒执行一次run方法,后面两个参数可根据自己的需求而定义
}
@Override
public void contextDestroyed(ServletContextEventsce) {
System.out.println("程序定时执行任务结束.....................................");
timer.cancel();
}
}
Web.xml配置:
<listener>
<listener-class>timer.TimerTaskManager</listener-class>
</listener>