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.
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 .
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.
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.
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.
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
This is the same, ScheduledThreadPoolExecutor is an implementation of ScheduledExecutorService
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