Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 104 ยท Coroutines and Background Work

WorkManager

Schedule reliable background work with WorkManager: workers, constraints, chained and periodic requests, expedited work, retries with backoff and observing status.

Coroutines are great for work that matters while the user is on a screen. But some work must happen even if the user closes the app: uploading a photo that was taken offline, syncing a database once a day, sending a log file when the phone is charging. A coroutine in viewModelScope dies with the screen, and a plain thread dies with the process. WorkManager is the Jetpack library for this kind of work: you describe a job and the conditions it needs, and the system runs it when those conditions hold, even after the app is killed or the phone reboots.

This lesson shows the pieces: the worker that does the job, the work request that describes when, constraints, chains, periodic and expedited work, retries with backoff, and how to observe the result. WorkManager needs a device and the system scheduler, so all WorkManager code is read-only here. The TryIts are stand-ins: a small scheduler written in plain Kotlin with a virtual clock, which follows the same rules so you can see the logic that the library applies for you.

When to use WorkManager

Pick the tool by how important the work is and when it must run:

Need Tool
Finish while the user is on the screen A coroutine in viewModelScope
Must finish eventually, even if the app is closed WorkManager
Runs at an exact time (an alarm clock, a calendar reminder) AlarmManager with exact alarms, see Services, Notifications and Foreground Work
Visible, ongoing, user-aware work (music, navigation, a long upload) A foreground service
Instant work started by a user action that is allowed to fail A coroutine

WorkManager promises that your work runs at least once, so design jobs so that running twice is harmless (uploading the same file again, or an update that overwrites). It does not promise an exact time: the system batches work to save battery.

A worker

A worker is a class with one method. The coroutine-friendly base class is CoroutineWorker:

Kotlin
// read-only example: needs WorkManager
class UploadWorker(
    appContext: Context,
    params: WorkerParameters,
) : CoroutineWorker(appContext, params) {

    override suspend fun doWork(): Result {
        val path = inputData.getString("path") ?: return Result.failure()

        return try {
            val url = uploadFile(path)                       // suspend call, runs on a background dispatcher
            Result.success(workDataOf("url" to url))
        } catch (e: IOException) {
            if (runAttemptCount < 4) Result.retry() else Result.failure()
        }
    }
}

doWork returns one of three results:

  • Result.success(outputData): finished. The optional output can feed the next worker in a chain.
  • Result.retry(): try again later, using the backoff policy (below).
  • Result.failure(): stop and do not retry. In a chain, this also cancels the work that depends on it.

Workers run in the background and are cancelled after about 10 minutes, so they are for short jobs. Data passes in and out through small key-value Data objects (a few kilobytes at most): pass a file path or an ID, never the file itself. Because a worker can be started in a fresh process, it must not rely on objects from a screen, and its dependencies must be created from the application context or injected, see Hilt.

Requests and constraints

A work request says what to run and when. A one-time request runs once; a periodic request repeats. Constraints describe the conditions the device must meet:

Kotlin
// read-only example
val constraints = Constraints.Builder()
    .setRequiredNetworkType(NetworkType.UNMETERED)   // Wi-Fi, no mobile data
    .setRequiresCharging(true)
    .setRequiresBatteryNotLow(true)
    .build()

val request = OneTimeWorkRequestBuilder<UploadWorker>()
    .setInputData(workDataOf("path" to "/data/user/0/app/cache/photo.jpg"))
    .setConstraints(constraints)
    .setInitialDelay(10, TimeUnit.MINUTES)
    .addTag("upload")
    .build()

WorkManager.getInstance(context)
    .enqueueUniqueWork("upload-photo", ExistingWorkPolicy.KEEP, request)

If the constraints are not met, the work simply waits; the system starts it when they become true, and stops it again if they stop being true while it runs (it then retries later). That is what makes WorkManager good for "when on Wi-Fi and charging".

enqueueUniqueWork gives the job a name, so pressing a button three times does not queue three uploads. The policy decides what happens when the name already exists: KEEP leaves the existing one, REPLACE cancels it and starts the new one, APPEND queues the new one after it.

Chaining work

Several workers can run in order, with each one's output becoming the next one's input:

Kotlin
// read-only example
WorkManager.getInstance(context)
    .beginWith(compressRequest)
    .then(uploadRequest)
    .then(cleanupRequest)
    .enqueue()

If a step ends with failure() (or is cancelled), the steps after it are cancelled too. Each step can have its own constraints, so compress can run immediately and upload wait for the network. The first stand-in models exactly that with a device that goes online and then starts charging.

flowchart LR
    C["compress<br/>(no constraints)"] --> U["upload<br/>(needs network)"]
    U --> K["cleanup<br/>(needs charging)"]
    U -. "failure" .-> X["cleanup CANCELLED"]

A chain is sequential. A failure stops everything after it; constraints delay each step separately.

Kotlin A chain of work with constraints (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the first run, compress completes immediately, upload waits one tick for the network, and cleanup waits one more tick for the charger, which is how constraints delay each step independently. In the second run, the rejected upload cancels cleanup.

Retries and backoff

When a worker returns Result.retry() (or a constraint stops being met during a run), WorkManager schedules another attempt after a backoff delay. You choose the policy and the initial delay:

Kotlin
// read-only example
val request = OneTimeWorkRequestBuilder<SyncWorker>()
    .setBackoffCriteria(
        BackoffPolicy.EXPONENTIAL,       // or LINEAR
        30, TimeUnit.SECONDS,
    )
    .build()
  • Linear: delays grow as base ร— attempt (30 s, 60 s, 90 s, ...).
  • Exponential: delays double each time (30 s, 60 s, 120 s, ...), which is gentler on a struggling server.

The default is exponential with a 30-second base; the minimum allowed is 10 seconds and the maximum delay is capped at 5 hours. WorkManager has no built-in attempt limit: if you retry forever, it retries forever. Read runAttemptCount in the worker and return failure() when you give up, as the UploadWorker above does.

The second stand-in runs three jobs on a virtual clock, with one linear policy, one exponential policy and one worker that gives up after three attempts.

Kotlin Retry with linear and exponential backoff (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Compare the two policies: upload (linear) waits 30 s and then 60 s, so it succeeds at 1:30, while sync (exponential) waits 30 s, 60 s and then 120 s, finishing at 3:30. report stops because its own code decided to return failure().

Periodic and expedited work

For work that repeats, use PeriodicWorkRequestBuilder:

Kotlin
// read-only example
val daily = PeriodicWorkRequestBuilder<CleanupWorker>(1, TimeUnit.DAYS)
    .setConstraints(Constraints.Builder().setRequiresCharging(true).build())
    .build()

WorkManager.getInstance(context)
    .enqueueUniquePeriodicWork("cleanup", ExistingPeriodicWorkPolicy.KEEP, daily)

The minimum interval is 15 minutes; shorter values are raised to 15. The interval is a target, not a schedule: the system may run the work anywhere inside the period, and can add a flex window to say "within the last 10 minutes of each period". Doze mode and App Standby can delay it further. Periodic work never runs on the exact minute, so use an alarm for that.

Expedited work is for short, important jobs that should start right away, such as sending a message the user just wrote. Mark the request with setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST). Expedited jobs have a daily quota, and the policy says what to do when the quota is used up: run as normal work, or drop the request. Expedited workers on older Android versions must provide a notification through getForegroundInfo(), because they run as a foreground service there. For jobs that last longer than a few minutes and need a visible notification, call setForeground(...) inside a worker.

Observing status

Each request has an ID, and optional tags and a unique name. WorkManager exposes the state as a Flow of WorkInfo, so your ViewModel can show progress without any polling:

Kotlin
// read-only example
val uploadState: StateFlow<String> =
    WorkManager.getInstance(context)
        .getWorkInfosForUniqueWorkFlow("upload-photo")
        .map { infos -> infos.firstOrNull()?.state?.name ?: "NONE" }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "NONE")

The states are ENQUEUED (waiting for its time or constraints), RUNNING, SUCCEEDED, FAILED, BLOCKED (waiting for the previous step in a chain) and CANCELLED. A worker can report progress with setProgress(...), which arrives in WorkInfo.progress. Collect these flows with the lifecycle rules from Collecting Flows Safely, and cancel with cancelUniqueWork("upload-photo") or cancelAllWorkByTag("upload").

Common mistakes

  • Using WorkManager for exact times. It is deferrable by design. Use an alarm for "at 7:00 sharp".
  • Doing work that is not idempotent. Retries and process restarts can run a worker twice.
  • Passing big objects through Data. Pass IDs and paths and load the rest inside the worker.
  • Enqueuing the same job on every launch. Use unique work with KEEP.
  • Retrying forever. Check runAttemptCount and return failure() at some point.
  • Expecting a periodic job every minute. The floor is 15 minutes, and it is approximate.
  • Using it for work that should stop with the screen. A search request belongs in a coroutine, see Coroutines on Android.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which job is the best fit for WorkManager?

    WorkManager is for deferrable work that must eventually run, with conditions, and survives app and device restarts. Screen work belongs in a coroutine, music in a foreground service and exact times in an alarm.
  2. 2. What happens to the later steps of a chain when one worker returns Result.failure()?

    A failed step cancels the work that depends on it, so a cleanup or notify step does not run after a failed upload.
  3. 3. What is the smallest repeat interval for periodic work?

    Shorter intervals are raised to 15 minutes, and even then the system chooses the exact moment inside the period.
  4. 4. With exponential backoff and a 30-second base, how long is the delay after the third failed attempt?

    Exponential delays double: 30 s after the first failure, 60 s after the second and 120 s after the third. Linear backoff would give 90 s after the third.
  5. 5. Why use enqueueUniqueWork with ExistingWorkPolicy.KEEP?

    A unique name means a repeated tap or app launch does not enqueue duplicate jobs; KEEP leaves the existing request alone.

Summary

  • WorkManager runs deferrable work reliably: it survives the app being closed and the device rebooting, with at-least-once semantics.
  • A CoroutineWorker returns success, retry or failure; data goes in and out as small Data maps.
  • Constraints (network, charging, battery, storage) make work wait until the device is ready.
  • Chains run steps in order and cancel the rest after a failure; unique work with KEEP, REPLACE or APPEND prevents duplicates.
  • Retries use linear or exponential backoff; limit attempts yourself with runAttemptCount.
  • Periodic work has a 15-minute minimum and an approximate schedule; expedited work is for short, urgent jobs within a quota.
  • Observe WorkInfo as a Flow. All WorkManager code here is read-only; the TryIts model constraints, chains and backoff.

Next: Services, Notifications and Foreground Work