Yoav Levavi
Yoav Levavi

Reputation: 85

How to cancel the timer on java?

How can I Cancel the timer when i2 == 690.

This is my code:

Timer timer = new Timer();
timer = new Timer(false);
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        if (i2 == 690) {
            timer.cancel();
        }
        i2--;
        System.out.println("Java " + i2);
    }
}, 0, 1000);

Upvotes: 1

Views: 2923

Answers (3)

You should cancel timerTask, if you want to cancel executing process timerTask.cancel(), but if you cancel all process after executing process timer.cancel();

Upvotes: 0

NESPowerGlove
NESPowerGlove

Reputation: 5496

You have to call TimerTask.cancel(). So just call this.cancel() in the run() method there, instead of on timer (as this will refer to the anonymous class instance that the run method belongs to).

If you need to cancel other tasks executed by the timer, Timer.cancel() will stop those as well (what you are currently doing), but does not stop the current executing TimerTask which is why the above cancel on the TimerTask is needed.

To quote from the Javadocs of Timer.cancel()

Does not interfere with a currently executing task (if it exists).

...

Note that calling this method from within the run method of a timer task that was invoked by this timer absolutely guarantees that the ongoing task execution is the last task execution that will ever be performed by this timer.

So combining both cancels should do the trick of canceling the entire Timer if that is what you need.

Upvotes: 4

SparkOn
SparkOn

Reputation: 8946

Try

if (i2 == 690) {
timer.cancel();
timer.purge(); 
return;
}

Timer#cancel()-Terminates this timer, discarding any currently scheduled tasks.Does not interfere with a currently executing task (if it exists)

Timer#purge() - Removes all cancelled tasks from this timer's task queue.

Upvotes: 2

Related Questions