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

Java 如何取消计时器的多个实例?,java,timer,Java,Timer,在下面的代码中,我创建了两个计时器实例(在执行命令之前和之后),如果命令成功运行,我将立即取消计时器,但在开始执行命令之前启动的计时器在指定时间后被取消,导致命令执行中断,如何取消第一个计时器实例,使命令执行不会中断 public class Tests { public static void main(String args[]) { try { detectHangingAndKillProject(30,false); // schedu

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

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);
            // ??
      }
    }
您可以让“DetectAngingAndKillProject”方法在执行命令之前返回您创建的计时器实例,然后在执行之后调用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;
}
您可以让“DetectAngingAndKillProject”方法在执行命令之前返回您创建的计时器实例,然后在执行之后调用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;
}

您需要保存对
计时器的引用
@ElliottFrisch以及如何保存?你的意思是说全球?你可以退货。如已发布的答案所示。您需要保存对
计时器的引用
@ElliottFrisch,以及如何保存?你的意思是说全球?你可以退货。如已发布的答案所示。