I have code where I schedule task using java.util.timer. I was looking around and saw ExecutorService can do the same. So this question here, have you used Timer and ExectuorService to schedule tasks , what is the benefit of one using over another.
Also wanted to check if anyone has uses the Timer class and ran into any issues which the ExecutorService solved it for them.
* Timer can be sensitive to changes in the system clock, ScheduledThreadPoolExecutor isn't
* Timer has only one execution thread, so long-running task can delay other tasks. ScheduledThreadPoolExecutor can be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providing ThreadFactory)
* runtime exceptions thrown in TimerTask kill that one thread, thus making Timer dead :-( ... i.e. scheduled tasks will not run anymore. ScheduledThreadExecutor not only catches runtime exceptions, but it lets you handle them if you want (by overriding afterExecute method from ThreadPoolExecutor). Task which threw exception will be canceled, but other tasks will continue to run.
If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
will give you a ScheduledExecutorService with similar functionality to Timer (i.e. it will be single-threaded) and but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer class). Using a ScheduledExecutorService also gives you advantages such as:
* you can customise it if need be (see the newScheduledThreadPoolExecutor() or the ScheduledThreadPoolExecutor class)
* the 'one off' executions can return results
About the only reasons for sticking to Timer I can think of are:
* it is available pre Java 5
* a similar class is provided in J2ME, which could make porting your application easier (but it wouldn't be terribly difficult to add a common layer of abstraction in this case)
An ExecutorService may be a thread pool, or even spread out across other systems in a cluster and do things like one-off batch execution, etc...
ScheduledExecutorService ses =
Executors.newScheduledThreadPool(1);
标签:tasks,Timer,will,VS,but,ScheduledExecutorService,ExecutorService
From: https://blog.51cto.com/u_16261339/7468627