Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for a Timer to finish in Java

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?

like image 852
ripper234 Avatar asked Aug 24 '09 10:08

ripper234


People also ask

What is delay in Timer Java?

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.

How do you schedule a Timer in Java?

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.

Can you set a Timer in Java?

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.

How do you stop a Timer in Java?

In order to cancel the Timer Task in Java, we use the java. util. TimerTask. cancel() method.


1 Answers

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.

like image 185
Mark Avatar answered Oct 07 '22 04:10

Mark