用Timer组件!可以定时执行动作!

解决方案 »

  1.   

    请问能否说的详细一点?我就是没有看明白啊,Timer 和 TimerTask  谢谢
      

  2.   

    private java.util.Timer timer = null;
    public void contextInitialized(ServletContextEvent event)
      {
            timer = new java.util.Timer(true);
            event.getServletContext().log("定时器已启动");
            timer.schedule(new MyTask(event.getServletContext()),0, 10*1000);
            event.getServletContext().log("已经添加任务调度表");
      }
    public void contextDestroyed(ServletContextEvent event)
      {
        timer.cancel();
        event.getServletContext();log("定时器销毁");
       }------------------------------------------------------
    public class MyTask extends TimerTask {
      private static final int C_SCHEDULE_HOUR = 22;
      private static boolean isRunning = false;
      private ServletContext context = null;  public MyTask(ServletContext context)
      {
              this.context = context;
      }  public void run()
      {
              Calendar cal = Calendar.getInstance();
              if (!isRunning)
              {
                      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("上一次任务执行还未结束");
              }
      }
    }
      

  3.   

    一个例子:
    import java.uitl.*;
    public class TimerTest{
    public static void main(String args[]){
    new TimerTest.do();}
    void do(){
    Timer t = new Timer(true);
    t.schedule(new Task(),50000L);
    }
    }
    class Task extends TimeTask{
    public void run(){
    System.out.println("This is task is running....");

    }