Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a timer in Java when required to set and cancel multiple times?

I need a certain block of code to execute after timer expires. But if flag is set, the timer must end immediately.

Using the inbuilt Timer class, I can schedule a task after a certain interval. The problem is that an instance of that class can only be scheduled and cancelled once, after which it gives an error that the timer has already been cancelled.

The simple solution would seem to be that I create a new instance of Timer each time. But that's not possible here since I have an infinite while loop, and I keep need to reusing the same instance.

An alternative is to use threads and create a custom timer function. I tried that, but threads don't execute immediately, and thus if I cancel my timer, it won't cancel immediately, but only when the thread is implemented after a few ms.

What other option do I have?

Also, please see https://stackoverflow.com/questions/19585841/timer-instance-in-loop-in-java

like image 772
sbhatla Avatar asked Jan 30 '26 12:01

sbhatla


1 Answers

Have a look at the ScheduledExecutorService

If you want to cancel a running task, you need to keep a reference to the Future<?> object returned when the task was submitted, then call cancel() on the future.

There are a shutDown() and a shutDownNow() method if you want do stop the executor permanently.

like image 186
Guillaume Avatar answered Feb 02 '26 02:02

Guillaume



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!