17

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?

Axxiss
  • 4,759
  • 4
  • 26
  • 45
pvllnspk
  • 5,667
  • 12
  • 59
  • 97
  • 2
    http://stackoverflow.com/questions/2333680/android-schedule-action – assylias Nov 09 '12 at 22:26
  • 2
    Main difference between Timer and ScheduledExecutor: the latter can use several thread (via a thread pool) and remove the risk of one task delaying the next one: http://stackoverflow.com/questions/409932/java-timer-vs-executorservice – assylias Nov 09 '12 at 22:28
  • This shows a good clarification http://stackoverflow.com/a/6558821/1016544 – Wahib Ul Haq Jan 29 '13 at 13:11

1 Answers1

5

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.

Max Hille
  • 661
  • 7
  • 18