I have this question:
I have a timer. With scheduleAtFixedRate it creates a new Timer task. In that timer task there is certain code, which may take a while to complete. How can I make sure that Timer won’t create new task when the previous one didn’t complete yet?
Thanks
My answer would be to not to use
Timer, it’s obsolete. Since Java5,Timerhas been superseded by theScheduledExecutorService, 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 withTimer.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:
With a
ScheduledExecutorService, instead of subclassingTimerTask, you subclassRunnabledirectly, 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 forScheduledExecutorServicecarefully), but the gist is something like this:As always, read the javadoc.