欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javaWeb中任务调度

程序员文章站 2022-07-15 07:51:28
...
package com.application;



import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ContextListener implements ServletContextListener {

private java.util.Timer timer = null;

public void contextInitialized(ServletContextEvent event) {
timer = new java.util.Timer(true);
event.getServletContext().log("定时器已启动");
timer.schedule(new TaskTime(event.getServletContext()), 0,
1000); //60 * 60
event.getServletContext().log("已经添加任务调度表");
}

public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
event.getServletContext().log("定时器销毁");
}

}












package com.application;

import java.util.Calendar;
import java.util.TimerTask;

import javax.servlet.ServletContext;

public class TaskTime extends TimerTask {

private static final int C_SCHEDULE_HOUR = 0;
private static boolean isRunning = false;
private ServletContext context = null;

public TaskTime(ServletContext context) {
this.context = context;
}

public void run() {
Calendar cal = Calendar.getInstance();
if (!isRunning) {
isRunning = true;
context.log("开始执行指定任务");

// TODO 添加自定义的详细任务,以下只是示例
int i = 0;
while (i++ < 10) {
context.log("已完成任务的" + i + "/" + 10);
}

isRunning = false;
context.log("指定任务执行结束");
// if (C_SCHEDULE_HOUR == cal.get(Calendar.HOUR_OF_DAY)) {
// isRunning = true;
// context.log("开始执行指定任务");
//
// // TODO 添加自定义的详细任务,以下只是示例
// int i = 0;
// while (i++ < 10) {
// context.log("已完成任务的" + i + "/" + 10);
// }
//
// isRunning = false;
// context.log("指定任务执行结束");
// }
} else {
context.log("上一次任务执行还未结束");
}
}

}