①监听类
public class TimerListener implements ServletContextListener {
private Timer timer = null;
public void contextInitialized(ServletContextEvent event) {
// 时间类
Calendar startDate = Calendar.getInstance();
long timeInterval = 1000 *60;
//设置开始执行的时间为 某年-某月-某月 00:00:00
//00:00:30准时更新之前提交了,没有开始出库的计划到今天计划中。
startDate.set(startDate.get(Calendar.YEAR), startDate.get(Calendar.MONTH), startDate.get(Calendar.DATE), 10, 43, 30);
timer = new Timer(true);
event.getServletContext().log("定时器已启动");
timer.scheduleAtFixedRate(new Task(), startDate.getTime(),timeInterval); // 每小时执行一次run方法 测试5秒5 * 1000
}
public void contextDestroyed(ServletContextEvent event) {
if (timer != null) {
timer.cancel();
event.getServletContext().log("定时器销毁");
}
}
}
②实现逻辑类
public class Task extends TimerTask {
private static boolean isRunning = false;
public void run() {
if (!isRunning) {
isRunning = true;
log.info("开始");
long start = System.currentTimeMillis();
int i=20;
while(i<10){
i=i-1;
}
log.info("结束");
long end = System.currentTimeMillis();
System.out.println("运行时间:" + (end - start) + "毫秒");
isRunning = false;
} else {
log.info("上一次任务执行还未结束,本次任务不能执行。");
}
}
}
③web配置监听
<!--timer-->
<listener>
<listener-class>cn.services.timer.TimerListener</listener-class>
</listener>