一共用三个类 可以执行 定时执行程序

package com.langchao.service.listener;
import java.util.Calendar;
import java.util.TimerTask;

import javax.servlet.ServletContext;

public class SendToOAAddAndDeleteUserInfoTask extends TimerTask{

private ServletContext context;

private static boolean isRunning = false;

private static boolean flag = true;

private static final int C_SCHEDULE_HOUR = 1;

public SendToOAAddAndDeleteUserInfoTask(ServletContext context) {

   this.context = context;

}

public void run() {

   Calendar cal = Calendar.getInstance();
   System.out.println(new java.util.Date());
  
   context.log("开始执行指定任务111");
   if (!isRunning) {
    context.log("------------开始执行指定任务22222 flag="+flag+" isRunning="+isRunning);
    context.log("&&&&&&&&&&&&&开始执行指定任务");
    context.log("*************指定任务执行结束");
   
    if (C_SCHEDULE_HOUR == cal.get(Calendar.HOUR_OF_DAY) && flag) {
    
     isRunning = true;
     context.log("开始执行指定任务");

     // TODO 此处添加自定义的详细任务

     isRunning = false;

     flag = false;

     context.log("指定任务执行结束");

    }

   } else {

    context.log("上一次任务执行还未结束");

   }

   if (C_SCHEDULE_HOUR != cal.get(Calendar.HOUR_OF_DAY)) {

    flag = true;

   }

}

}

package com.langchao.service.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class TimerListener implements ServletContextListener {

private java.util.Timer timer = null;

private SendToOAAddAndDeleteUserInfoTask task;

public void contextInitialized(ServletContextEvent event) {

   // todo auto-generated method stub

   timer = new java.util.Timer(true);

   //reportTask = new ReportTask(event.getServletContext());

   event.getServletContext().log("定时器已启动");
   //timer.schedule(task, time)

   timer.schedule(new SendToOAAddAndDeleteUserInfoTask(event.getServletContext()),0,100*200);

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

}

public void contextDestroyed(ServletContextEvent event) {

   // todo auto-generated method stub

   timer.cancel();

   event.getServletContext().log("定时器销毁");

}

}

 

web.xml:

<listener>
<listener-class>TimerListener</listener-class>
</listener>