ScheduledThreadPoolExecutor 仅“打勾"一次 [英] ScheduledThreadPoolExecutor only "ticking" once
问题描述
我使用 CountDownTimer
来实现我的 Activity
中的一些倒计时功能.我决定远离 CountDownTimer
并使用 ScheduledThreadPoolExecutor
因为 CountDownTimer
s 不能在 onTick()
中取消自己.
I was using a CountDownTimer
for some countdown functionality I have in my Activity
. I decided to move away from CountDownTimer
and use ScheduledThreadPoolExecutor
because CountDownTimer
s can't cancel themselves in onTick()
.
出于某种原因,我在以下代码中的 Runnable
只执行一次.我不确定为什么它不执行多次.destroyCountdownTimer()
函数没有被命中.
For some reason, my Runnable
in the following code only executes once. I'm not sure why it isn't executing multiple times. The destroyCountdownTimer()
function is not getting hit.
private ScheduledThreadPoolExecutor mCountdownTimer;
private Tick mTick;
class Tick implements Runnable {
@Override
public void run() {
Log.e("tick", String.valueOf(mAccumulatedMilliseconds));
mAccumulatedMilliseconds += 1000;
populateTimeAccumulated();
populateTimeRemaining();
updatePercentages();
if (mTotalMilliseconds <= mAccumulatedMilliseconds) {
destroyCountdownTimer();
}
}
}
private void startCountdown() {
if (mAccumulatedMilliseconds < mTotalMilliseconds) {
mCounterIsRunning = true;
if (mCountdownTimer == null) {
mCountdownTimer = new ScheduledThreadPoolExecutor(1);
}
if (mTick == null) {
mTick = new Tick();
}
mCountdownTimer.scheduleAtFixedRate(mTick, 1000, 1000, TimeUnit.MILLISECONDS);
}
}
private void destroyCountdownTimer() {
if (mCountdownTimer != null) {
mCountdownTimer.shutdownNow();
mCountdownTimer = null;
}
if (mTick != null) {
mTick = null;
}
}
推荐答案
文档说:
If any execution of the task encounters an exception, subsequent executions are suppressed.
将 try-catch 块添加到您的 Tick runnable.
Add try-catch block to your Tick runnable.
这篇关于ScheduledThreadPoolExecutor 仅“打勾"一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!