ScheduledThreadPoolExecutor only “ticking” once

老子叫甜甜 提交于 2019-12-24 05:13:05

问题


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 CountDownTimers can't cancel themselves in onTick().

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;
    }
}

回答1:


The documentation says:

If any execution of the task encounters an exception, subsequent executions are suppressed.

Add try-catch block to your Tick runnable.



来源:https://stackoverflow.com/questions/29522243/scheduledthreadpoolexecutor-only-ticking-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!