如何取消多个计时器实例?

时间:2016-05-10 13:39:32

标签: java timer

在下面的代码中,我创建了2个计时器实例(执行命令之前和之后),如果命令运行成功我立即取消计时器,但是在启动命令执行之前启动的计时器在指定时间后取消导致命令执行中断,如何取消第一个定时器实例,这样就不会中断命令执行?

public class Tests {
      public static void main(String args[]) {
        try {
          detectHangingAndKillProject(30,false);  // schedule a task to kill the example.exe after 5 minutes
          Process p = Runtime.getRuntime().exec("command to run");
          detectHangingAndKillProject(0,true);  // if the above command runs successfully cancel the timer right away
          ..
          ..
      }
    }
   }

计时器任务如下:

class ReminderTask extends TimerTask{
        @Override
        public void run() {
            try {
                System.out.println("Will kill example.exe now");
                Process exec = Runtime.getRuntime().exec("taskkill /F /IM example.exe");
                // timer.cancel()  ??
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void detectHangingAndKillProject(int seconds, boolean needToCancelTimer){
        Timer tmr=new Timer();
        if(needToCancelTimer){
            tmr.cancel();
            tmr.purge();
        }else{
            Tests t=new Tests();
            tmr.schedule(t.new ReminderTask(), seconds*10000);
            // ??
      }
    }

1 个答案:

答案 0 :(得分:2)

您可以使“detectHangingAndKillProject”方法在执行命令之前返回您创建的计时器实例,然后在执行后调用cancel和purge

public class Tests {
    public static void main(String args[]) {
        try {
            Timer tmr = detectHangingAndKillProject(30,false);
            Process p = Runtime.getRuntime().exec("command to run");
            tmr.cancel();
            tmr.purge();
            ..
            .. 
        }
    }
}

public static Timer detectHangingAndKillProject(int seconds){
    Timer tmr=new Timer();
    Tests t=new Tests();
    tmr.schedule(t.new ReminderTask(), seconds*10000);
    return tmr;
}