Search code examples
androidrunnable

ScheduledThreadPoolExecutor only "ticking" once


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

Solution

  • The documentation says:

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

    Add try-catch block to your Tick runnable.