Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScheduledExecutorService or ScheduledThreadPoolExecutor

I'm building an Android App which have to periodically do something in a Service. And I found that using ScheduledThreadPoolExecutor and ScheduledExecutorService is preferable to Timer.

Can anyone explain the difference between ScheduledExecutorService and ScheduledThreadPoolExecutor and which one is more suitable for Android?

Update

I just found this article and this post explain the difference between several way to implement repeating periodic tasks. In my case, ScheduledThreadPoolExecutor and AlarmManager is more suitable.

like image 518
changbenny Avatar asked Sep 10 '15 10:09

changbenny


People also ask

What is the difference between ExecutorService and ScheduledExecutorService?

ScheduledExecutorService is an ExecutorService which can schedule tasks to run after a delay, or to execute repeatedly with a fixed interval of time in between each execution. Tasks are executed asynchronously by a worker thread, and not by the thread handing the task to the ScheduledExecutorService .

What is a ScheduledExecutorService?

public interface ScheduledExecutorService extends ExecutorService. An ExecutorService that can schedule commands to run after a given delay, or to execute periodically. The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution.

What is ScheduledThreadPoolExecutor?

ScheduledThreadPoolExecutor class in Java is a subclass of ThreadPoolExecutor class defined in java. util. concurrent package. As it is clear from its name that this class is useful when we want to schedule tasks to run repeatedly or to run after a given delay for some future time. It creates a fixed-sized Thread Pool.

Can we use scheduler in Executor framework?

To execute a task in this scheduled executor after a period of time, you have to use the schedule() method. This method receives the following three parameters: The task you want to execute. The period of time you want the task to wait before its execution.


2 Answers

ScheduledExecutorService is an interface (a contract) and ScheduledThreadPoolExecutor implements that interface.

Since you cannot directly instantiate an interface, you have to use implementation through instantiating ScheduledThreadPoolExecutor directly or through means of factory method such as java.util.concurrent.Executors that returns an instance of ScheduledThreadPoolExecutor.

e.g

ScheduledExecutorService scheduler =
 Executors.newScheduledThreadPool(1);

scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS); //returns a ScheduledFuture

Have a look at Scheduled Executor Service Usage for Andriod

like image 65
Ravindra babu Avatar answered Sep 25 '22 09:09

Ravindra babu


This is the same, ScheduledThreadPoolExecutor is an implementation of ScheduledExecutorService

like image 23
fab Avatar answered Sep 25 '22 09:09

fab