Resettable Java Timer
According to the Timer
documentation, in Java 1.5 onwards, you should prefer the ScheduledThreadPoolExecutor
instead. (You may like to create this executor using Executors
.newSingleThreadScheduledExecutor()
for ease of use; it creates something much like a Timer
.)
The cool thing is, when you schedule a task (by calling schedule()
), it returns a ScheduledFuture
object. You can use this to cancel the scheduled task. You're then free to submit a new task with a different triggering time.
ETA: The Timer
documentation linked to doesn't say anything about ScheduledThreadPoolExecutor
, however the OpenJDK version had this to say:
Java 5.0 introduced the
java.util.concurrent
package and one of the concurrency utilities therein is theScheduledThreadPoolExecutor
which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for theTimer
/TimerTask
combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassingTimerTask
(just implementRunnable
). ConfiguringScheduledThreadPoolExecutor
with one thread makes it equivalent toTimer
.
If your Timer
is only ever going to have one task to execute then I would suggest subclassing it:
import java.util.Timer;import java.util.TimerTask;public class ReschedulableTimer extends Timer{ private Runnable task; private TimerTask timerTask; public void schedule(Runnable runnable, long delay) { task = runnable; timerTask = new TimerTask() { @Override public void run() { task.run(); } }; this.schedule(timerTask, delay); } public void reschedule(long delay) { timerTask.cancel(); timerTask = new TimerTask() { @Override public void run() { task.run(); } }; this.schedule(timerTask, delay); }}
You will need to work on the code to add checks for mis-use, but it should achieve what you want. The ScheduledThreadPoolExecutor
does not seem to have built in support for rescheduling existing tasks either, but a similar approach should work there as well.
The whole Code snippet goes like this .... I hope it will be help full
{ Runnable r = new ScheduleTask(); ReschedulableTimer rescheduleTimer = new ReschedulableTimer(); rescheduleTimer.schedule(r, 10*1000); public class ScheduleTask implements Runnable { public void run() { //Do schecule task } }class ReschedulableTimer extends Timer { private Runnable task; private TimerTask timerTask; public void schedule(Runnable runnable, long delay) { task = runnable; timerTask = new TimerTask() { public void run() { task.run(); } }; timer.schedule(timerTask, delay); } public void reschedule(long delay) { System.out.println("rescheduling after seconds "+delay); timerTask.cancel(); timerTask = new TimerTask() { public void run() { task.run(); } }; timer.schedule(timerTask, delay); } }}