1,定时执行的类
package com.utils;import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date;
public class MyTimer extends Thread {// 间隔时间:小时private int intervalHours;// 误差(操作所需时间可能导致误差):分钟private int deviationMinute;// 执行时间private String runTime;public MyTimer(){// 参数取得intervalHours = 24;deviationMinute = 5;runTime= "19:30";}public void run() {while (!this.isInterrupted()) {// 线程未中断执行循环// 获取当前时间:HH:mmDate now = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");String hours = dateFormat.format(now); // 时间到达if(hours.equals(runTime)){doRun();try {// 长时间休眠:间隔时间-误差Thread.sleep(intervalHours * 3600 * 1000 - deviationMinute * 60 * 1000);} catch (InterruptedException e) {e.printStackTrace();}}else{try {// 等待间隔:30sThread.sleep(30000);System.out.println(hours);} catch (InterruptedException e) {e.printStackTrace();}}}}/*** 处理*/private void doRun() {} }
2,servlet
package com.utils;import javax.servlet.http.HttpServlet;public class MyServlet extends HttpServlet{/*** */private static final long serialVersionUID = 1L;private MyTimer myTimer; public MyServlet(){ } public void init(){ String str = null; if (str == null && myTimer== null) { myTimer= new MyTimer();myTimer.start(); }
super.init(); } public void destory(){ if (myTimer!= null && myTimer.isInterrupted()) { myTimer.interrupt(); }
super.destroy(); } }
3,web.xml
<servlet><servlet-name>MyServlet</servlet-name><servlet-class>com.utils.MyServlet</servlet-class><load-on-startup>9</load-on-startup
</servlet>