Schedule and manage background tasks in Compose Multiplatform
An app may need to synchronize data, upload files, or perform other work when users aren't actively interacting with it. The APIs available for scheduling this work differ by platform:
Android provides WorkManager, as well as specialized APIs for exact alarms and foreground services.
iOS provides the Background Tasks framework for refresh and processing work.
Desktop apps can use JVM APIs such as
ScheduledExecutorServicefor work in the app process, or integrate with operating-system services when work needs to continue after the app exits.Web apps can use Web Workers, Service Workers, or browser APIs such as Background Sync. Availability and execution behavior depend on the browser.
On mobile platforms, the operating system determines when background work can run based on factors such as battery state, network availability, and system resource limits. Therefore, treat the scheduled time as the earliest possible start time rather than an exact execution time.
Compose Multiplatform doesn't provide a common background-task API. For Android and iOS, the KMP WorkManager community library offers a common API for scheduling background work.
Use KMP WorkManager on Android and iOS
KMP WorkManager provides a shared API on top of Android WorkManager and iOS BGTaskScheduler. It lets you manage background work without implementing the scheduling logic separately on each platform.
The library currently supports Android and iOS only. Supported platform versions, setup requirements, and APIs can change, so check the library's installation and platform setup guide before using it.
You can implement background logic in your commonMain code, but define workers in the corresponding androidMain and iosMain files. In this example, scheduleSync() schedules a registered SyncWorker to run when a network connection is available. Launch it from a coroutine scope in your app:
With ExistingPolicy.KEEP, reusing the same id prevents the scheduler from adding another instance of the task. To cancel the task, call cancel() with the same id:
KMP WorkManager also supports periodic work, execution constraints, retries, task state observation, task chains, and group cancellation. For worker registration and scheduling options, see the library's quick start.
Both Android and iOS impose execution limits. See the library's constraints and triggers guide for platform differences, as well as the iOS best practices and the troubleshooting guide.
What's next
Learn how to add dependencies on multiplatform libraries.