從我的閱讀中,似乎ScheduledExecutorService是在Java中啓動和停止計時器的正確方法。使用ScheduledExecutorService啓動和停止計時器
我需要移植一些啓動和停止計時器的代碼。這不是週期性的計時器。該代碼在啓動之前停止計時器。所以,實際上每個開始都是重新啓動()。我正在尋找使用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, 盧布
代碼因爲寫入不會編譯:startTimer()中的_batchTimer沒有在任何地方聲明。 如果您可以詳細瞭解預期行爲,那麼這會有所幫助:startTimer和stopTimer的返回值是多少?爲什麼你想讓start/stopTimer成爲潛在的阻塞呼叫? – Sbodd 2010-06-23 18:02:00
@Sbodd,當我開始一個計時器時,如果已經有一個計時器正在運行,我想停止它,這樣我就沒有兩個計時器同時彈出。我認爲,而不是get()那裏,我只需要在未來的實例上調用cancel()。 – rouble 2010-06-23 18:09:11