I'm using java.util.Timer to schedule a periodic task. At one point, I'd like to shut it down, and wait for it to finish.
Timer.cancel() will prevent any future tasks from running. How do I make sure any tasks are not running at the moment (or wait for them if they are?)
I can introduce external synchronization mechanisms, but I don't see how they can cover all cases. For example, if I synchronize on some Monitor within the task, I still miss the case when the task just started executing but didn't take the monitor.
What is the recommended practice for waiting until all tasks are really done, including currently running tasks?
The delay parameter is used to set both the initial delay and the delay between event firing, in milliseconds. Once the timer has been started, it waits for the initial delay before firing its first ActionEvent to registered listeners.
Java Timer schedule() methodThe schedule (TimerTask task, Date time) method of Timer class is used to schedule the task for execution at the given time. If the time given is in the past, the task is scheduled at that movement for execution.
Add the following code to the Java file: timer = new Timer(countdown, this); Notice the "countdown" variable is used. This parameter sets up the timer to trigger a Java function after 10 seconds.
In order to cancel the Timer Task in Java, we use the java. util. TimerTask. cancel() method.
You would be better using an ScheduledExecutorService instead of a Timer to schedule your periodic task. ScheduledExecutorService provides a shutdown() method that will execute any pending tasks. You can then call awaitTermination() to wait for shutdown() to finish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With