Where Do I Create and Use Scheduledthreadpoolexecutor, Timertask, or Handler

Where do I create and use ScheduledThreadPoolExecutor, TimerTask, or Handler?

I prefer to use ScheduledThreadPoolExecutor. Generally, if I understand your requirements correctly, all these can be implemented in your activity, TimerTask and Handler are not needed, see sample code below:

public class MyActivity extends Activity {
private ScheduledExecutorService scheduleTaskExecutor;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scheduleTaskExecutor= Executors.newScheduledThreadPool(5);

// This schedule a task to run every 10 minutes:
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
// Parsing RSS feed:
myFeedParser.doSomething();

// If you need update UI, simply do this:
runOnUiThread(new Runnable() {
public void run() {
// update your UI component here.
myTextView.setText("refreshed");
}
});
}
}, 0, 10, TimeUnit.MINUTES);
} // end of onCreate()
}

Remember to finish/close your runnable task properly in Activity.onDestroy(), hope that help.

TimerTask vs Thread.sleep vs Handler postDelayed - most accurate to call function every N milliseconds?

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

ScheduledThreadPoolExecutor deals properly with all these issues and it does not make sense to use Timer.. There are two methods which could be of use in your case.. scheduleAtFixedRate(...) and scheduleWithFixedDelay(..)

class MyTask implements Runnable {

@Override
public void run() {
System.out.println("Hello world");
}
}

ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
long period = 100; // the period between successive executions
exec.scheduleAtFixedRate(new MyTask(), 0, period, TimeUnit.MICROSECONDS);
long delay = 100; //the delay between the termination of one execution and the commencement of the next
exec.scheduleWithFixedDelay(new MyTask(), 0, delay, TimeUnit.MICROSECONDS);

handler.postDelayed vs ScheduledThreadPoolExecutor.scheduleWithFixedDelay

Handler - Execute a Runnable task on the UIThread after an optional delay

ScheduledThreadPoolExecutor - Execute periodic tasks with a background thread pool

scheduleWithFixedDelay

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

Handler

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

  1. to schedule messages and runnables to be executed as some point in the future; and

  2. to enqueue an action to be performed on a different thread than your own.

Android - Run a thread repeatingly within a timer

Just simply use below snippet

private final Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
//
// Do the stuff
//

handler.postDelayed(this, 1000);
}
};
runnable.run();

To stop it use

handler.removeCallbacks(runnable);

Should do the trick.

ScheduledExecutorService or ScheduledThreadPoolExecutor

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

How to schedule tasks in a specific thread without using a looper and a handler?

You can create a ScheduledThreadPoolExecutor with one single thread using Executors.newSingleThreadScheduledExecutor().

Optionally, you can pass a ThreadFactory as parameter if you want to have more control about this single thread. The thread factory's newThread(Runnable) method is called every time the executor wants to have a new Thread instance that should run the given Runnable (which is not identical to the Runnable you pass to the executor's execute(...), submit(...) or schedule(...) methods).

Note that you are not able to reuse an existing thread, as there is no way to 'inject' code into an already running thread in general, as it is possible in Qt. There, every thread has its own event queue and timing facility, so you can freely decide which (already existing) thread should process your timed task (see Timers in Qt).

There is no such feature in Java out of the box.



Related Topics



Leave a reply



Submit