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
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.
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
How to to Check If a User Has Rated Your App on the Google Play
Javadoc in Eclipse Failing to Recognize Packages
Android Studio Build.Gradle Warning Message
Android Recyclerview Findviewholderforadapterposition Returns Null
Error: Failed to Resolve: Com.Android.Support:Appcompat-V7:29.0.1'
How to Create an Avd for Android 4.0
Starting Activity from Fragment Causes Nullpointerexception
Send Touch Events to a Device via Adb
How to Check the Multiple Permission at Single Request in Android M
Android Studio Fails to Build New Project, Timed Out While Wating for Slave Aapt Process
Using the Limit Statement in a SQLite Query
Pagination Not Work for the Recyclerview Within Nestedscrollview
How Could I Filter the Listview Using Baseadapter
Error Inflating Class and Android.Support.V7.Widget.Cardview