TimerTask runs one more time after I call timer.ca

2019-07-29 12:55发布

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条回答
冷血范
2楼-- · 2019-07-29 13:27

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.

查看更多
登录 后发表回答