What are the pros and cons of using ScheduledExecutorService
/ Timer
/ Handler
? As I understand in Android instead of Timer
it's need to use Handler
, but what about ScheduledExecutorService
?
As I understand Handler
and ScheduledExecutorService
is only for relative time, right?
The Java TimerTask and the Android Handler both allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handler over TimerTask in Android (see here, here, here, here, here, and here).
According to Java Concurrency in Practice: 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.
All three allow you to execute tasks on a different (eg. non-main) thread. The Handler allows you to use a message passing Actor pattern to communicate safely between thread. It does not allow you to do timing/delays/etc.
A ScheduledExecutorService is a very generic threading management solution. You initialize it with a certain number to worker threads and then give it work units. You can delay/time and repeat work units.
The Timer class has a simple API which resembles a ScheduledExecutorService for one-time, one-thread usage. The official API suggests to not use this class but roll your own ScheduledExecutor instead.
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