Reputation: 359
In below code I am creating 2 instances of timer(before and after executing command), if the command runs successfully I am cancelling the timer right away, but the timer started before starting command execution gets cancelled after specified time resulting in command execution interruption, how to cancel the first timer instance so there will no interruption in command execution ?
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
..
..
}
}
}
Timer tasks as below :
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);
// ??
}
}
Upvotes: 0
Views: 287
Reputation: 66
You could make the "detectHangingAndKillProject" method return the instance of timer you create before excecuting the command and then call cancel and purge after the excecution
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;
}
Upvotes: 2