How to cancel a timer schedule

I am currently using a timer to execute some function every time interval. However, later, when I want to change the execution interval of a function, I cannot cancel the previous schedule. how can this be solved? Thanks

+6
source share
2 answers

Using the timer.cancel() method, you can cancel the timer and all scheduled tasks. (see API documentation ), or you can call the undo method on your TimerTask timertask.cancel() (see API documentation )

If you want to change the scheduled time, you must cancel TimerTask and add a new TimerTask.

+5
source

You can learn ScheduledThreadPoolExecutor instead of Timer .

Use is pretty straight forward. You create an instance of the executor:

 ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor( 1 ); 

And then when you want to add the task that you are calling:

 executor.scheduleAtFixedRate( myRunnable, delay, interval, unit ); 

Where myRunnable is your task (which implements Runnable -interface), the delay is how long before the task needs to be completed for the first time, interval is the time between the execution of the task after the first execution. delay and interval are evaluated based on the unit parameter, which may be TimeUnit. * (where * - SECONDS, MINUTES, MILLISECONDS, etc.).

Then, to stop execution, you call:

 executor.shutdownNow(); 

And then you can resubmit your task at a different interval.

Note. You may need to create a new instance of the artist before resubmitting your task, but I don’t quite understand why.

+3
source

Source: https://habr.com/ru/post/900184/


All Articles