在工程的WEB-INF/web.xml配置文件中加入如下三行,所计划的任务就会在Web容器(或服务器)启动时自动开始执行了: <listener> <listener-class>com.xxh.autoTask.ProjectServletContextListner</listener-class> </listener>
ProjectServletContextListner.javapackage com.xxh.autoTask;
import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;
public class ProjectServletContextListner implements ServletContextListener {
//定时器 private static java.util.Timer timer = null; //此方法仅在关闭Web容器(或服务器)时被调用一次 public void contextDestroyed(ServletContextEvent event) { // TODO Auto-generated method stub timer.cancel(); event.getServletContext().log("定时器已销毁,任务执行结束"); }
//此方法仅在起动Web容器(或服务器)时被调用一次 public void contextInitialized(ServletContextEvent event) { // TODO Auto-generated method stub timer = new java.util.Timer(true); javax.servlet.ServletContext ctx = event.getServletContext(); ctx.log("定时器已启动,任务开始执行"); /* //如果是用web.xml文件配置参数,则用下面的方式读取参数设置值 long period = Long.valueOf((String)ctx.getInitParameter("period")).longValue(); */ timer.schedule(new NewTask(), // 所需要执行的任务 0, // 延迟时间(0 --- 表示起动Web容器(或服务器)就立即执行此任务) 30*1000 // 任务的执行间隔时间[单位:毫秒] (此处的间隔时间是30秒) ); }
}
CustomTask.javapackage com.xxh.autoTask;
public interface CustomTask { /** * 用于实现自定义的任务 */ public void execute();
}
CustomTask.javapackage com.xxh.autoTask;
public class MyTask implements CustomTask {
public void execute() { // TODO Auto-generated method stub System.out.println("在此方法中实现任务的主体"); }
}
NewTask.javapackage com.xxh.autoTask;
import java.util.TimerTask;
public class NewTask extends TimerTask {
private static boolean isRunning = false; //运行标志(表示是否正在运行计划的任务) private static int t = 3; private CustomTask ct = TaskFactory.getTask(); @Override public void run() { // TODO Auto-generated method stub if(!isRunning){ //当未执行此任务时则开始执行 if(ct != null){ isRunning = true; //将任务执行标志设置为正在执行 ct.execute(); //执行任务 isRunning = false; //将任务执行标志设置为执行完毕 }else{ if(t == 0) return; t--; System.out.println(); System.out.println("[Error] [com.xxh.autoTask.NewTask] The task is null."); System.out.println("[Error] [com.xxh.autoTask.NewTask] The task is null."); System.out.println("[Error] [com.xxh.autoTask.NewTask] The task is null."); } }else{ System.out.println("The task is running."); }
}
}
TaskFactory.javapackage com.xxh.autoTask;
public class TaskFactory {
/** * 功能:返回实现了CustomTask接口的类的实例对象 * * * 例: 如果实现了CustomTask接口的类名是MyTask, * return new MyTask(); * 如上这样就可以了. */ public static CustomTask getTask(){ return new MyTask(); } }