@capgo/capacitor-background-task
v8.1.12
Published
Capacitor plugin for periodic background fetch tasks on iOS and Android.
Readme
@capgo/capacitor-background-task
Run periodic background tasks in your Capacitor app on iOS and Android, with named tasks that survive app restarts. Sync data or refresh content while the app is not open.
🤖 Building with an AI coding agent? Install Capgo skills so Claude Code, Codex, Cursor, Copilot, or Gemini CLI know how to install and use
@capgo/capacitor-background-taskin your Capacitor app:npx skills add Cap-go/capgo-skills. Then ask your agent: "Add @capgo/capacitor-background-task to my Capacitor app and wire it up." Agent setup guides · Hosted MCP
Key features
- Named tasks:
registerTaskAsync()andunregisterTaskAsync()with options likeminimumIntervalandrequiresNetwork. - Status:
isTaskRegisteredAsync(),getRegisteredTasksAsync()andgetStatusAsync()report what is scheduled and available. - Missed runs:
getPendingTaskRunsAsync()returns runs recorded natively before JavaScript was ready. - Testing:
triggerTaskWorkerForTestingAsync()runs all registered tasks right away during development. - Familiar API: an Expo BackgroundTask style API plus React Native background-task compatible
schedule(),cancel()andfinish(). - Platforms: iOS and Android. iOS uses BackgroundTasks, Android uses WorkManager. Web is a stub.
What It Does
- Schedules periodic background work on Android with WorkManager.
- Schedules background processing on iOS with BGTaskScheduler.
- Supports multiple named tasks with
minimumIntervalin minutes. - Emits retained task events so task runs recorded before JavaScript is ready can be drained.
- Provides a small
react-native-background-taskcompatible API:define,schedule,cancel,statusAsync, andfinish.
Limits
- Background tasks are not exact timers. Android and iOS decide when work actually runs.
- Android enforces a 15 minute minimum interval.
- iOS may delay runs substantially based on battery, network, and user behavior.
- iOS background tasks do not run in the simulator; use a physical device.
- This plugin cannot make an app run indefinitely in the background.
Compatibility
| Plugin version | Capacitor compatibility | Maintained | | -------------- | ----------------------- | ---------- | | v8.*.* | v8.*.* | ✅ | | v7.*.* | v7.*.* | On demand | | v6.*.* | v6.*.* | On demand |
Policy:
- New plugins start at version
8.0.0(Capacitor 8 baseline). - Backward compatibility for older Capacitor majors is supported on demand.
Install
You can use our AI-Assisted Setup to install the plugin. Add the Capgo skills to your AI tool using the following command:
npx skills add https://github.com/cap-go/capacitor-skills --skill capacitor-pluginsThen use the following prompt:
Use the `capacitor-plugins` skill from `cap-go/capacitor-skills` to install the `@capgo/capacitor-background-task` plugin in my project.If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:
npm install @capgo/capacitor-background-task
npx cap synciOS Setup
Add the background processing mode and permitted task identifier to ios/App/App/Info.plist:
<key>UIBackgroundModes</key>
<array>
<string>processing</string>
</array>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>app.capgo.backgroundtask.processing</string>
</array>Usage
Define tasks at module scope so they are available as soon as the app is started by the OS.
import { BackgroundTask, BackgroundTaskResult } from '@capgo/capacitor-background-task';
const SYNC_TASK = 'sync-offline-data';
BackgroundTask.defineTask(SYNC_TASK, async () => {
try {
await fetch('https://example.com/sync', { method: 'POST' });
return BackgroundTaskResult.Success;
} catch {
return BackgroundTaskResult.Failed;
}
});
await BackgroundTask.registerTaskAsync(SYNC_TASK, {
minimumInterval: 30,
requiresNetwork: true,
});Testing
await BackgroundTask.triggerTaskWorkerForTestingAsync();React Native Compatibility
import { BackgroundTask } from '@capgo/capacitor-background-task';
BackgroundTask.define(async () => {
await fetch('https://example.com/sync', { method: 'POST' });
});
await BackgroundTask.schedule({
period: 1800,
});Example App
The example-app/ folder is linked via file:.. and is intended for validating native wiring during development.
API
defineTask(...)registerTaskAsync(...)unregisterTaskAsync(...)isTaskRegisteredAsync(...)getRegisteredTasksAsync()getPendingTaskRunsAsync()getStatusAsync()triggerTaskWorkerForTestingAsync()addExpirationListener(...)define(...)schedule(...)cancel()statusAsync()finish(...)- Interfaces
- Type Aliases
- Enums
defineTask(...)
defineTask(taskName: string, callback: BackgroundTaskCallback) => voidDefine the JavaScript callback for a task. Call this at module/global scope.
| Param | Type |
| -------------- | ------------------------------------------------------------------------- |
| taskName | string |
| callback | BackgroundTaskCallback |
registerTaskAsync(...)
registerTaskAsync(taskName: string, options?: BackgroundTaskOptions | undefined) => Promise<void>Register a named periodic background task.
| Param | Type |
| -------------- | ----------------------------------------------------------------------- |
| taskName | string |
| options | BackgroundTaskOptions |
unregisterTaskAsync(...)
unregisterTaskAsync(taskName: string) => Promise<void>Unregister a named periodic background task.
| Param | Type |
| -------------- | ------------------- |
| taskName | string |
isTaskRegisteredAsync(...)
isTaskRegisteredAsync(taskName: string) => Promise<boolean>Check whether a named task is registered.
| Param | Type |
| -------------- | ------------------- |
| taskName | string |
Returns: Promise<boolean>
getRegisteredTasksAsync()
getRegisteredTasksAsync() => Promise<string[]>Return all registered task names.
Returns: Promise<string[]>
getPendingTaskRunsAsync()
getPendingTaskRunsAsync() => Promise<BackgroundTaskEvent[]>Return pending task runs that native recorded before JavaScript was ready.
Returns: Promise<BackgroundTaskEvent[]>
getStatusAsync()
getStatusAsync() => Promise<BackgroundTaskStatus>Return native background task availability.
Returns: Promise<BackgroundTaskStatus>
triggerTaskWorkerForTestingAsync()
triggerTaskWorkerForTestingAsync() => Promise<boolean>Trigger all registered tasks immediately for development/testing.
Returns: Promise<boolean>
addExpirationListener(...)
addExpirationListener(listener: (event: BackgroundTaskEvent) => void) => Promise<PluginListenerHandle>Listen for iOS expiration callbacks.
| Param | Type |
| -------------- | --------------------------------------------------------------------------------------- |
| listener | (event: BackgroundTaskEvent) => void |
Returns: Promise<PluginListenerHandle>
define(...)
define(callback: BackgroundTaskCallback) => voidReact Native background-task compatible single-task define helper.
| Param | Type |
| -------------- | ------------------------------------------------------------------------- |
| callback | BackgroundTaskCallback |
schedule(...)
schedule(options?: ReactNativeBackgroundTaskOptions | undefined) => Promise<void>React Native background-task compatible single-task scheduler.
| Param | Type |
| ------------- | --------------------------------------------------------------------------------------------- |
| options | ReactNativeBackgroundTaskOptions |
cancel()
cancel() => Promise<void>React Native background-task compatible single-task cancel helper.
statusAsync()
statusAsync() => Promise<ReactNativeBackgroundTaskStatus>React Native background-task compatible status helper.
Returns: Promise<ReactNativeBackgroundTaskStatus>
finish(...)
finish(result?: BackgroundTaskResult | undefined) => Promise<void>React Native background-task compatible finish helper. Normal Expo-style callbacks are finished automatically.
| Param | Type |
| ------------ | --------------------------------------------------------------------- |
| result | BackgroundTaskResult |
Interfaces
BackgroundTaskEvent
Payload emitted when native scheduling asks JavaScript to run a task.
| Prop | Type | Description |
| --------------- | -------------------- | ----------------------------------------------------------------------------------------------------------- |
| taskName | string | Name passed to registerTaskAsync. |
| taskId | string | Native run identifier. The JavaScript wrapper finishes it automatically when the defined callback resolves. |
| timestamp | number | Native timestamp for the run. |
| test | boolean | True when triggered through triggerTaskWorkerForTestingAsync. |
BackgroundTaskOptions
Options for registering a periodic background task.
| Prop | Type | Description |
| --------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| minimumInterval | number | Inexact interval in minutes between task runs. Defaults to 720 minutes. Android enforces a 15 minute minimum. iOS treats this as an earliest begin date and may run much later. |
| requiresNetwork | boolean | Require an active network before running the native scheduler. Defaults to true. |
PluginListenerHandle
| Prop | Type |
| ------------ | ----------------------------------------- |
| remove | () => Promise<void> |
ReactNativeBackgroundTaskOptions
React Native background-task compatible schedule options.
| Prop | Type | Description |
| ------------- | ------------------- | -------------------------------------------------------------------------- |
| period | number | Desired seconds between each execution. Mapped to minimumInterval minutes. |
| timeout | number | Android-only timeout hint kept for API compatibility. |
ReactNativeBackgroundTaskStatus
React Native background-task compatible status payload.
| Prop | Type | Description |
| ----------------------- | -------------------- | -------------------------------------------------- |
| available | boolean | Whether background tasks are available to the app. |
| unavailableReason | string | Reason when unavailable. |
Type Aliases
BackgroundTaskCallback
Function executed for a background task.
(event: BackgroundTaskEvent): void | BackgroundTaskResult | Promise<void | BackgroundTaskResult>
Enums
BackgroundTaskResult
| Members | Value | Description |
| ------------- | -------------- | ------------------------------- |
| Success | 1 | The task finished successfully. |
| Failed | 2 | The task failed. |
BackgroundTaskStatus
| Members | Value | Description |
| ---------------- | -------------- | -------------------------------------------------------- |
| Restricted | 1 | Background task scheduling is unavailable or restricted. |
| Available | 2 | Background task scheduling is available. |
