Skip to content

Repeating Periodic Tasks

nesquena edited this page Oct 17, 2014 · 14 revisions

Overview

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:

  1. Handler - Execute a Runnable task on the UIThread after an optional delay
  2. ScheduledThreadPoolExecutor - Execute periodic tasks with a background thread pool
  3. AlarmManager - Execute any periodic task in the background as a service
  4. TimerTask - Doesn't run in UIThread and is not reliable. Consensus is to never use TimerTask

Recommended methods are outlined below.

Handler

Using a handler to execute Runnable code involves creating a Handler and then instructing this object to run things:

// Create the Handler object 
Handler handler = new Handler();
// Execute a runnable task as soon as possible
handler.post(runnableCode);
// Define the task to be run here
private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {
      // Do something here
      Log.e("Handlers", "Called");
      // Repeat this runnable code block every 2 seconds
      mHandler.postDelayed(mRunnable, 2000);
    }
};

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 so you can safely update the user interface within the runnable code block. see this handler post and this other handler post for reference.

ScheduledThreadPoolExecutor

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.

AlarmManager

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.

References

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.

Clone this wiki locally