skip to content

In WorkManager, a nightly cleanup runs as unique periodic work; how do the 15-minute floor, the flex interval and ExistingPeriodicWorkPolicy decide when it runs and which version runs?

level: seniorimportance: should knowfreq 52%

answer

  1. clamped, not rejected
  2. flex window at the period's end
  3. periodic never SUCCEEDED
  4. UPDATE keeps the schedule
  5. KEEP keeps the old spec

basics

~20 s

PeriodicWorkRequest clamps intervals under 15 minutes to 15 with a log warning, and a flexInterval of at least 5 minutes confines runs to the end of each period. ExistingPeriodicWorkPolicy.UPDATE applies a new spec without resetting the schedule; KEEP keeps the old one.

solid answer

~40 s

`PeriodicWorkRequestBuilder<CleanupWorker>(24, TimeUnit.HOURS, 2, TimeUnit.HOURS)` sets a repeat interval and a flex interval. The interval can't go below `MIN_PERIODIC_INTERVAL_MILLIS`, 15 minutes: a shorter value is silently clamped with a log warning, not rejected. The flex interval, at least 5 minutes, makes the work eligible only in the last part of each period. The interval is a minimum gap, and unmet constraints can delay or skip a run. Periodic work never reaches `SUCCEEDED`; after each run it goes back to `ENQUEUED`, and only `CANCELLED` ends it. I enqueue it with `enqueueUniquePeriodicWork("nightly-cleanup", ExistingPeriodicWorkPolicy.UPDATE, request)`: since WorkManager 2.8 `UPDATE` applies a changed spec from the next run, keeps the original enqueue time and doesn't interrupt a running worker. `KEEP` would keep the old spec forever, and `CANCEL_AND_REENQUEUE`, the old `REPLACE`, cancels it and restarts the period.

code

kotlin · 20 lines
kotlin
fun scheduleNightlyCleanup(context: Context) {
    val request = PeriodicWorkRequestBuilder<CleanupWorker>(
        24, TimeUnit.HOURS, // repeatInterval
        2, TimeUnit.HOURS, // flexInterval: eligible in the last 2 hours of each period
    )
        .setConstraints(
            Constraints.Builder()
                .setRequiresCharging(true)
                .setRequiresStorageNotLow(true)
                .build()
        )
        .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 1, TimeUnit.MINUTES)
        .build()

    WorkManager.getInstance(context).enqueueUniquePeriodicWork(
        "nightly-cleanup",
        ExistingPeriodicWorkPolicy.UPDATE,
        request,
    )
}

go deeper

for a junior

Recall the 15-minute minimum, that the interval is a minimum gap rather than a timer, and that periodic work is scheduled with PeriodicWorkRequestBuilder.

for a middle

Explain the flex window, why periodic work never reports SUCCEEDED, and what each ExistingPeriodicWorkPolicy value does to work already scheduled.

for a senior

Diagnose why an updated spec never reaches existing installs, choose UPDATE for enqueue-on-start code, and read the clamping warning when an interval looks wrong.

for a principal

Set a team default for periodic enqueue sites (one constant name, UPDATE policy) and decide which schedules justify setNextScheduleTimeOverride instead of plain intervals.

## The interval floor A `PeriodicWorkRequest` repeats with a **repeat interval** that is the *minimum* time between runs, not an exact timer. The smallest allowed value is `PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS`, **15 minutes**. Asking for less does not throw: WorkManager clamps the value up to 15 minutes and logs the warning "Interval duration lesser than minimum allowed value". A team that writes `PeriodicWorkRequestBuilder<SyncWorker>(5, TimeUnit.MINUTES)` gets a 15-minute job and may never notice unless someone reads the log. The actual run time also depends on constraints and on the OS batching jobs. If the cleanup requires charging and the phone is never charged during an interval, that run is delayed, or effectively skipped. ## The flex interval The four-argument builder, `PeriodicWorkRequestBuilder<CleanupWorker>(24, TimeUnit.HOURS, 2, TimeUnit.HOURS)`, adds a **flex interval**. The documented window starts at `repeatInterval - flexInterval` and lasts to the end of the period, so with these numbers the cleanup is eligible only in the last two hours of each 24-hour cycle. - The flex interval must be at least `MIN_PERIODIC_FLEX_MILLIS`, **5 minutes**, and at most the repeat interval; values outside that range are clamped with a warning. - Without a flex interval the **first** run is eligible right after enqueueing (plus any `setInitialDelay`). With one, the first run waits `repeatInterval - flexInterval`. - `setInitialDelay()` on periodic work delays only the first run. ## What a periodic run's result means | `doWork()` returns | Effect on periodic work | |---|---| | `Result.success()` | back to `ENQUEUED` for the next period | | `Result.failure()` | also back to `ENQUEUED`; the next period still runs | | `Result.retry()` | rerun after the backoff delay instead of waiting for the next period | Periodic work has **one terminal state, `CANCELLED`**; it never reports `SUCCEEDED` or `FAILED`. A UI that waits for `SUCCEEDED` on a periodic request waits forever: read `outputData` or `progress`, or count runs instead. ## Unique periodic work and `ExistingPeriodicWorkPolicy` `enqueueUniquePeriodicWork(name, policy, request)` is typically called on every app start, so the policy decides what happens to the request that is already scheduled. | Policy | Effect on existing unfinished periodic work | |---|---| | `KEEP` | nothing changes; the new request is ignored | | `UPDATE` | the existing work takes the new spec from its next run; the enqueue time is kept, so the period is not reset, and a running worker is not interrupted | | `CANCEL_AND_REENQUEUE` | the existing work is cancelled and deleted, then the new request is enqueued and its period starts again | | `REPLACE` | deprecated since 2.8 and identical to `CANCEL_AND_REENQUEUE` | The trap with `KEEP`: periodic work is never finished unless cancelled, so a new constraint or interval shipped in an app update **never takes effect** on devices that already had the old request. `UPDATE` is the default worth teaching. `CANCEL_AND_REENQUEUE` is for a deliberate reset, for example after changing the worker's input in a way the old run must not see. To change a request that was enqueued by ID, `WorkManager.updateWork()` does the same in-place update, and `WorkInfo.generation` increases with each update. `updateWork()` cannot turn a one-time request into a periodic one; that still needs a cancel and a new request. ## Choosing values for the nightly cleanup 1. Pick the interval from the business need (once a day), not from how fresh the data could be; the OS treats it as a minimum anyway. 2. Add a flex window only when *when* in the period matters, for example the last two hours of the day, and keep it at least 5 minutes. 3. Add constraints that make the run cheap (charging, storage not low) and accept that they can skip a day. 4. Set backoff for transient errors, and make the worker idempotent, because a stopped run is retried. ## Pitfalls to name in an interview - Periodic requests **cannot be expedited**: building one with `setExpedited()` throws `IllegalArgumentException` ("PeriodicWorkRequests cannot be expedited"). - `setBackoffCriteria()` combined with a `setRequiresDeviceIdle(true)` constraint throws at `build()` ("Cannot set backoff criteria on an idle mode job"). - Backoff is clamped between 10 seconds and 5 hours. - For a run at a specific time, `setNextScheduleTimeOverride()` (since 2.9.0) sets the next run's time; pair it with `UPDATE` so rescheduling does not cancel a running worker. - Two different names for the same cleanup schedule two cleanups. Keep the name in one constant.

  • A periodic sync returns Result.retry(); does it wait for the next period?
    No. A periodic request that returns `Result.retry()` goes back to `ENQUEUED` and is rescheduled by its backoff policy, by default exponential from 30 seconds and capped at five hours, rather than at the next period boundary. `Result.failure()` is different: it just waits for the next period, because periodic work never ends in `FAILED`.
  • You changed the cleanup's constraints in a new release, but logs show old devices still use the old ones; why?
    The app enqueues with `ExistingPeriodicWorkPolicy.KEEP`. Periodic work stays `ENQUEUED` or `RUNNING` until it is cancelled, so `KEEP` always finds existing work and ignores the new request. Switch to `UPDATE`, which applies the new spec from the next run and keeps the schedule, or to `CANCEL_AND_REENQUEUE` if the period should restart.

  • Building a PeriodicWorkRequest with a 5-minute interval throws an exception at build().
  • Periodic work moves to SUCCEEDED after each successful run.
  • ExistingPeriodicWorkPolicy.UPDATE cancels the worker that is running right now.
  • With KEEP, a changed constraint shipped in an app update reaches existing installs.
  • The repeat interval guarantees a run exactly every interval.
  • A periodic request can be expedited to run its first period immediately.

Assumes WorkManager 2.12; ExistingPeriodicWorkPolicy.UPDATE and CANCEL_AND_REENQUEUE arrived in 2.8.0, which deprecated REPLACE.