13

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.

Community
  • 1
  • 1
changbenny
  • 358
  • 6
  • 17

4 Answers4

9

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

Corical
  • 15
  • 5
Ravindra babu
  • 42,401
  • 8
  • 208
  • 194
3

This is the same, ScheduledThreadPoolExecutor is an implementation of ScheduledExecutorService

Ravindra babu
  • 42,401
  • 8
  • 208
  • 194
fab
  • 782
  • 6
  • 10
2

Creating ScheduledThreadPoolExecutor Using Executors

you can also look this one

http://tutorials.jenkov.com/java-util-concurrent/scheduledexecutorservice.html

if you want to use it periodically, you should use this method

scheduleAtFixedRate (Runnable, long initialDelay, long period, TimeUnit timeunit)

Community
  • 1
  • 1
0

Simple Example hopefully it may help

public class MyTask implements Runnable {

    public MyTask() {
    }

    public void run() {
        System.out.println(Thread.currentThread().getName());
        System.out.println("File uploading is start1");

        System.out.println("file uploaded");
    }

}

public class ScheduledExecutorsTest {
    public ScheduledExecutorsTest() {
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int time = 10 ;
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        MyTask myTask = new MyTask();
        //scheduledExecutorService.scheduleAtFixedRate(myTask, 0L, 9L, TimeUnit.SECONDS);
        scheduledExecutorService.schedule(myTask, 3L, TimeUnit.SECONDS);

        scheduledExecutorService.shutdown();
    }

}
Adrian Mole
  • 30,672
  • 69
  • 32
  • 52