I read in a comment to this answer and in many other questions about scheduling (sorry, no references) that java.util.Timer
is deprecated. I really hope not since I'm using it as the light way to schedule things in Java (and it works nicely). But if it's deprecated, I'll look elsewhere. However, a quick look at the API docs for 1.6 doesn't say anything about it being deprecated. It's not even mentioned in Sun's Deprecated List.
Is it officially deprecated* and if so, what should I use instead?
* On the other hand, if it's not deprecated, could people stop badmouthing this innocent and brilliantly-implemented set-o-classes?
Java Timer class is thread safe and multiple threads can share a single Timer object without need for external synchronization.
Java programming language provides a class utility known as Timer Task. It allows one to schedule different tasks. In other words, a task can be executed after a given period or at a specified date and time. A Timer in Java is a process that enables threads to schedule tasks for later execution.
The java. util. Timer class provides facility for threads to schedule tasks for future execution in a background thread. This class is thread-safe i.e multiple threads can share a single Timer object without the need for external synchronization.
Keep a reference to the timer somewhere, and use: timer. cancel(); timer. purge();
As others have mentioned, no it is not deprecated but I personally always use ScheduledExecutorService
instead as it offers a richer API and more flexibility:
ScheduledExecutorService
allows you to specify the number of threads whereas Timer
always uses a single thread.ScheduledExecutorService
can be constructed with a ThreadFactory
allowing control over thread aspects other than the name / daemon status (e.g. priority, ThreadGroup
, UncaughtExceptionHandler
).ScheduledExecutorService
allows tasks to be scheduled with fixed delay as well as at a fixed rate.ScheduledExecutorService
accepts Callable
/ Runnable
as it's unit of work, meaning that you don't need to subclass TimerTask
specifically to use it; i.e. you could submit the same Callable
implementation to a regular ExecutorService
or a ScheduledExecutorService
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With