Zhangali Bidaibekov
Zhangali Bidaibekov

Reputation: 701

TimerTask runs one more time after I call timer.cancel() method

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

Upvotes: 2

Views: 279

Answers (1)

evilpenguin
evilpenguin

Reputation: 5478

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.

Upvotes: 5

Related Questions