Two-week programme · Day 3 of 14
Ninety-two minutes of nothing
Part 1Basics
Priya's change is safe on disk, but the app is closed, and closed apps run no code. Something outside the app has to start it again.
That something is the operating system. You can't tell a phone to run your code at 4:12 pm. You can only ask it to run your code once a condition is true, such as the network being available, and it decides the exact moment.
Words you need today
- Background work
- Code that runs with no screen showing.
- WorkManager
- The Android library for requesting background work. It remembers your request even across a reboot.
- Constraint
- A condition the work needs, such as a network connection.
- BGTaskScheduler
- The iOS equivalent. It gives far fewer guarantees about when your code runs.
- Coalescing
- Combining many requests into one, so five reasons to sync become one sync.
- Budget
- How long the OS lets your background work run, usually a few minutes.
The story
From 2:40 to 4:12 pm, none of your code runs. That is correct behaviour: a phone that polled from a basement would burn battery and achieve nothing.
At 4:12 pm Priya climbs the stairs and the phone finds a network. Android sees that a waiting job's network condition is now met, starts your process in the background, and calls the sync worker with a budget of about eight minutes. No screen opens. Priya has no idea it happened.
Part 2Today's question
With the app closed, who decides when your code runs?
By the end of this lesson, you should be able to:
- Explain why background timing is a request, not a schedule
- Compare what Android and iOS allow
- Explain how five triggers become one job
Part 3In detail
Step by step
- Ask at save time. When Priya saves, the app requests a sync job that requires a network. The request is stored by the OS's scheduler, not by your app.
- The app can die. From now on your process doesn't need to exist. The request is already safe.
- The condition is met. Priya walks upstairs and the phone finds a network.
- The OS starts your app. Android starts your process in the background, with no screen, and calls your worker.
- The worker runs within its budget. It syncs, and if it runs out of time it reports what is left, and a follow-up job finishes the rest.
You ask, the OS decides
You can't schedule background work on a phone. You can only request it with conditions, and the OS picks the moment based on battery, network and how often the user opens your app.
Android's WorkManager keeps your request across reboots and honours conditions such as requires network. iOS gives far less: BGTaskScheduler runs when the system chooses, which may be hours later. On iOS, sync when the app opens carries more of the weight, and background URLSession handles big transfers.
Many triggers, one job
In one minute a phone can produce five reasons to sync: an edit, the app backgrounding, Wi-Fi returning, a push and a timer. Starting five syncs wastes battery and creates races. A trigger hub coalesces them into one unique job.
Budgets are real
The worker may be stopped at any time. So the engine must stop cleanly at its budget and report whether work remains. A follow-up job handles the rest, and nothing depends on one run finishing.
The same request, in Android's API
1fun requestSync(context: Context, reason: String) {2 val work = OneTimeWorkRequestBuilder<SyncWorker>()3 .setConstraints(4 Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()5 )6 .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)7 .setInputData(workDataOf("reason" to reason))8 .build()9 10 // KEEP: five triggers in one minute still mean one job.11 WorkManager.getInstance(context)12 .enqueueUniqueWork("sync", ExistingWorkPolicy.KEEP, work)13}This one uses the Android API, so it runs on a device rather than in our tests. Priya's save called it at 2:40 pm, and the job waited 92 minutes.
The code, explained
This is the real code, and our tests run it. Read each block, then the notes under it.
Every trigger becomes one job
Edits, pushes, timers and reconnects all want a sync. Without this funnel, a busy minute would start five of them.
1/** The part of WorkManager this code needs. Returns false when a job with this name already waits. */2fun interface JobScheduler {3 fun enqueueUnique(name: String, requiresNetwork: Boolean): Boolean4}5 6/** Every reason to sync comes through here, and they all become the same one job. */7class TriggerHub(private val scheduler: JobScheduler) {8 var lastTrigger: Trigger? = null9 private set10 11 fun fire(trigger: Trigger): Boolean {12 lastTrigger = trigger13 return scheduler.enqueueUnique("sync", requiresNetwork = true)14 }15}fun interface JobScheduler- The one WorkManager feature this code needs. Hiding it behind an interface lets a plain test run this code.
enqueueUnique("sync", ...)- On Android this is enqueueUniqueWork with KEEP: if a job named sync already waits, nothing new is added.
requiresNetwork = true- The condition the OS waits for. Your code doesn't watch the network at all.
Compiled and tested by npm run test:mobile.
The worker, and its time budget
The OS gives you a few minutes. This code spends them, and leaves things tidy if it runs out.
1sealed interface WorkResult {2 /** Done. The worker enqueues a follow-up job when [morePending] is true. */3 data class Success(val morePending: Boolean) : WorkResult4 data object Retry : WorkResult5}6 7/** What the Android worker does, with no Android types, so a plain test can run it. */8class SyncWork(9 private val engine: SyncEngine,10 private val hub: TriggerHub,11 private val clockMs: () -> Long,12 private val budgetMs: Long = 8 * 60_000,13) {14 suspend fun doWork(): WorkResult {15 val deadline = clockMs() + budgetMs16 return when (val out = engine.run(hasTime = { clockMs() < deadline })) {17 is RunOutcome.Finished -> {18 if (out.morePending) hub.fire(Trigger.PERIODIC)19 WorkResult.Success(out.morePending)20 }21 is RunOutcome.RetryLater -> WorkResult.Retry // the OS applies its own backoff22 RunOutcome.AlreadyRunning -> WorkResult.Success(morePending = false)23 is RunOutcome.RebuildNeeded -> WorkResult.Success(morePending = false)24 }25 }26}deadline = clockMs() + budgetMs- Eight minutes, a little under what Android allows, so the code stops itself before the OS stops it.
hasTime = { ... }- The engine checks this between batches, so it always stops at a safe point.
if (out.morePending) hub.fire(...)- Leftover work gets a follow-up job, so nothing depends on one run finishing.
RetryLater -> WorkResult.Retry- Tells the OS to apply its own backoff. The ops are still in the outbox.
Compiled and tested by npm run test:mobile.
What can go wrong
- Five triggers arrive in a minute
- All of them enqueue one uniquely named job, so only one sync runs.
- iOS doesn't run your task for hours
- Sync when the app opens as well. Never rely on the background alone on iOS.
- The OS stops your worker midway
- Finished work is already recorded, so the next run continues from there.
Decisions to defend
- How do you keep sync running on Android? Unique WorkManager job with a network constraint, not a long-running service. A service with no user-visible purpose gets killed, and Android restricts starting one from the background.
Part 4Questions and answers
Answer out loud first, then open each one.
With KEEP, an edit arrives during a running sync. Is it lost?
A manufacturer's phones run periodic jobs 70% less often. What do you do?
Part 5Going further
The three questions, for today
- Where does it live?
- The job request, kept on disk by WorkManager.
- Who runs the next step?
- The OS, when the network condition is met.
- What if it runs twice?
- A unique job name: five triggers, one job.
Practise
Optional reference pages
You don’t need these for the lesson. They hold more detail if you want it later.
The worker has started and has eight minutes. Tomorrow it does its job: 37 ops up, 140 changes down.