定時器
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>