I\'d like to have a java.utils.Timer with a resettable time in java.I need to set a once off event to occur in X seconds. If nothing happens in between the time the timer wa
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.concurrentpackage and one of the concurrency utilities therein is theScheduledThreadPoolExecutorwhich is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for theTimer/TimerTaskcombination, as it allows multiple service threads, accepts various time units, and doesn't require subclassingTimerTask(just implementRunnable). ConfiguringScheduledThreadPoolExecutorwith one thread makes it equivalent toTimer.