根据我的阅读,ScheduledExecutorService 似乎是在 Java 中启动和停止计时器的正确方法。
我需要移植一些启动和停止计时器的代码。这不是一个周期性定时器。此代码在启动计时器之前停止计时器。所以,实际上每次启动实际上都是一个restart()。我正在寻找使用 ScheduledExecutorService 的正确方法。这是我想出的。寻找我所缺少的东西的评论和见解:
ScheduledExecutorService _Timer = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> _TimerFuture = null;
private boolean startTimer() {
try {
if (_TimerFuture != null) {
//cancel execution of the future task (TimerPopTask())
//If task is already running, do not interrupt it.
_TimerFuture.cancel(false);
}
_TimerFuture = _Timer.schedule(new TimerPopTask(),
TIMER_IN_SECONDS,
TimeUnit.SECONDS);
return true;
} catch (Exception e) {
return false;
}
}
private boolean stopTimer() {
try {
if (_TimerFuture != null) {
//cancel execution of the future task (TimerPopTask())
//If task is already running, interrupt it here.
_TimerFuture.cancel(true);
}
return true;
} catch (Exception e) {
return false;
}
}
private class TimerPopTask implements Runnable {
public void run () {
TimerPopped();
}
}
public void TimerPopped () {
//Do Something
}
tia, 卢布