My answer would be to not to use Timer
, it's obsolete. Since Java5, Timer
has been superseded by the ScheduledExecutorService
, which is much more flexible and easier to use. You get finer control over how the scheduler works, the sort of control you don't get with Timer
.
You create one using the Executors factory class, which has a number of factory methods. The one you should be looking at is newSingleThreadScheduledExecutor, which should do exactly what you're looking for:
Creates a single-threaded executor
that can schedule commands to run
after a given delay, or to execute
periodically. Tasks are guaranteed to
execute sequentially, and no more than
one task will be active at any given
time.
With a ScheduledExecutorService
, instead of subclassing TimerTask
, you subclass Runnable
directly, and then submit the task to the executor. There are various methods on the executor, you need to pick which one is suitable for your needs (read the javadoc for ScheduledExecutorService
carefully), but the gist is something like this:
// initialise the executor
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
while (tasksRemaining) {
// create your task
Runnable task = ....;
// submit it to the executor, using one of the various scheduleXYZ methods
executor.schedule(task, delay, unit);
}
// when everything is finished, shutdown the executor
executor.shutdown();
As always, read the javadoc.