I use ScheduledExecutorService
to start a timer that runs periodically, but this timer can't be canceled after I calling the cancel()
:
import java.util.concurrent.*;
public class Monitor {
private static ScheduledFuture<?> timerCtrl;
private final ScheduledExecutorService scheduExec = Executors.newScheduledThreadPool(1, StatmonitorThreadFactory.getInstance());
private void startTimer() {
timerCtrl = scheduExec.scheduleAtFixedRate(new MonitorTimer(), 5, 5, TimeUnit.SECONDS);
}
public boolean cancelMonitorTimer() {
if (timerCtrl != null) {
timerCtrl.cancel(false); //both timerCtrl.isDone() and timerCtrl.isCancelled() return true
LOG.error("{} {}", timerCtrl.isDone(), timerCtrl.isCancelled());
if (!timerCtrl.isCancelled()) {
LOG.error("timerCtrl cancel failed!");
return false;
}
}
return true;
}
private class MonitorTimer implements Runnable {
@Override
public void run() {
doPeriodicMonitor(); //call another function
}
}
}
At first, I call startTimer()
to start my timer. After a while, I call cancelMonitorTimer
to cancel and stop this timer and the function return true but timer still runs, doPeriodicMonitor
is called every 5 seconds which is a period set by myself in startTimer
.