-
Notifications
You must be signed in to change notification settings - Fork 6.3k
Repeating Periodic Tasks
Repeating periodic tasks within an application is a common requirement. This functionality can be used for polling new data from the network, running manual animations, or simply updating the UI. There are at least four ways to run periodic tasks:
-
Handler - Execute a
Runnable
task on the UIThread after an optional delay - ScheduledThreadPoolExecutor - Execute periodic tasks with a background thread pool
- AlarmManager - Execute any periodic task in the background as a service
- TimerTask - Doesn't run in UIThread and is not reliable. Consensus is to never use TimerTask
Recommended methods are outlined below.
We can use a Handler to repeat code at an interval by constructing a Handler
and then "posting" Runnable
code to the event message queue on the thread to be processed.
Using a Handler
to execute arbitrary code once after a delay:
// We need to use this Handler package
import android.os.Handler;
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the task to be run here
private Runnable runnableCode = new Runnable() {
@Override
public void run() {
// Do something here on the main thread
Log.d("Handlers", "Called on main thread");
}
};
// Repeat this runnable code again every 2 seconds
handler.postDelayed(runnableCode, 2000);
We can also use a handler to execute a periodic runnable task as demonstrated below:
// We need to use this Handler package
import android.os.Handler;
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the task to be run here
private Runnable runnableCode = new Runnable() {
@Override
public void run() {
// Do something here on the main thread
Log.d("Handlers", "Called on main thread");
// Repeat this same runnable code again every 2 seconds
handler.postDelayed(runnableCode, 2000);
}
};
// Kick off the first runnable task right away
handler.post(runnableCode);
Remove the scheduled execution of a runnable with:
// Removes pending code execution
handler.removeCallbacks(runnableCode);
Note that with a Handler
, the Runnable
executes in UIThread
by default so you can safely update the user interface within the runnable code block. See this handler post and this other handler post for reference.
Refer to our threads and handlers guide for a more advanced breakdown.
A pool of threads which can schedule commands to execute periodically in the background. Useful when multiple worker threads are needed but generally not needed. See this guide on how they work or this stackoverflow post.
This should be used if the periodic tasks need to run in the background even when the app is not in the foreground. This leverages the alarm service on the phone to cause periodic executions of a service which will run continuously until stopped. See the AlarmManager section of the services guide for details.
- http://www.mopri.de/2010/timertask-bad-do-it-the-android-way-use-a-handler/
- http://stackoverflow.com/questions/18605403/timertask-vs-thread-sleep-vs-handler-postdelayed-most-accurate-to-call-functio
- http://androidtrainningcenter.blogspot.in/2013/12/handler-vs-timer-fixed-period-execution.html
- http://stackoverflow.com/questions/8098806/where-do-i-create-and-use-scheduledthreadpoolexecutor-timertask-or-handler
Created by CodePath with much help from the community. Contributed content licensed under cc-wiki with attribution required. You are free to remix and reuse, as long as you attribute and use a similar license.
Finding these guides helpful?
We need help from the broader community to improve these guides, add new topics and keep the topics up-to-date. See our contribution guidelines here and our topic issues list for great ways to help out.
Check these same guides through our standalone viewer for a better browsing experience and an improved search. Follow us on twitter @codepath for access to more useful Android development resources.