TimerTask runs one more time after I call timer.ca

2019-07-29 13:36发布

问题:

TimerTask runs one more time after I call timer.cancel() method. I don't need TimerMethod to be executed after I call stopBusTimer() method.

Can somebody explain why is it happening?

busTimer = new Timer();
    busTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            TimerMethod(mSelectedRoute);
        }
    }, 0, Consts.BUS_TIMER_INTERVAL);


 private void stopBusTimer() {
    if (busTimer != null) {
        busTimer.cancel();
        busTimer.purge();     
        busTimer = null;
        Log.v(LOG_TAG, "stop BusTimer");
    }
}

回答1:

The cancel method will stop all following executions, but not the current one. It your method execution takes a long time, then it is possible by the time you call cancel, the method has already begun executing.

The best way to make sure the method does not execute is to call cancel from within the run() function itself.