Reputation: 1283
How should I choose between new ScheduledThreadPoolExecutor(1).scheduleWithFixedDelay
or Handler.postDelayed()
?
Are they same? What are the differences between them?
Future scheduledFuture = scheduledExecutor.scheduleWithFixedDelay(runnable, 0, delay, TimeUnit.MILLISECONDS);
new Handler().postDelayed(runnable, delay);
Upvotes: 2
Views: 1506
Reputation: 69689
Handler
- Execute a Runnable task on the UIThread after an optional delay
ScheduledThreadPoolExecutor
- Execute periodic tasks with a background thread pool
scheduleWithFixedDelay
Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor.
ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit)
There are some disadvantages of using Timer
It creates only single thread to execute the tasks and if a task takes too long to run, other tasks suffer.
It does not handle exceptions thrown by tasks and thread just terminates, which affects other scheduled tasks and they are never run
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
Handler
was designed for
to schedule messages and runnables to be executed as some point in the future; and
to enqueue an action to be performed on a different thread than your own.
Upvotes: 1
Reputation: 1694
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.
A Handler is a Class that is used to communicate between Threads. Handler runs on the Thread whose Looper you have passed to it. If your Handler is instantiated in MainThread then it runs on the MainThread , If you create a Worker Thread with Looper (HandlerThread) and pass it's Looper to Handler ,then it run's on that worker thread.
Basically both of them Execute the task after a delay, but Do note that
scheduledExecutor.scheduleWithFixedDelay
will always execute in the worker thread , were asHandler.postDelayed
will run on Thread where it has been attached to (Either MainThread or BackGround Thread)
Upvotes: 1