@capgo/capacitor-background-task

中文文档
8.1.12发布于 2026/10/15MPL-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 4万

Capacitor plugin for periodic background fetch tasks on iOS and Android.

原始使用文档
文档目录29 节
  1. ➡️ Get started for free
  2. Key features
  3. What It Does
  4. Limits
  5. Compatibility
  6. Install
  7. iOS Setup
  8. Usage
  9. Testing
  10. React Native Compatibility
  11. Example App
  12. API
  13. defineTask(...)
  14. registerTaskAsync(...)
  15. unregisterTaskAsync(...)
  16. isTaskRegisteredAsync(...)
  17. getRegisteredTasksAsync()
  18. getPendingTaskRunsAsync()
  19. getStatusAsync()
  20. triggerTaskWorkerForTestingAsync()
  21. addExpirationListener(...)
  22. define(...)
  23. schedule(...)
  24. cancel()
  25. statusAsync()
  26. finish(...)
  27. Interfaces
  28. Type Aliases
  29. Enums

@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.

Capgo - Build Capacitor apps with AI, ship updates instantly

Capgo: push fixes to your Capacitor users in minutes, build signed iOS and Android apps without a Mac, and roll back in one click.

➡️ Get started for free

14-day unlimited free trial. No credit card required

🤖 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-task in 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

@capgo/capacitor-background-task for Capacitor apps

Key features

  • Named tasks: registerTaskAsync() and unregisterTaskAsync() with options like minimumInterval and requiresNetwork.
  • Status: isTaskRegisteredAsync(), getRegisteredTasksAsync() and getStatusAsync() 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() and finish().
  • 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 minimumInterval in minutes.
  • Emits retained task events so task runs recorded before JavaScript is ready can be drained.
  • Provides a small react-native-background-task compatible API: define, schedule, cancel, statusAsync, and finish.

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 versionCapacitor compatibilityMaintained
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-plugins

Then 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 sync

iOS 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(...)

defineTask(taskName: string, callback: BackgroundTaskCallback) => void

Define the JavaScript callback for a task. Call this at module/global scope.

ParamType
taskNamestring
callbackBackgroundTaskCallback

registerTaskAsync(...)

registerTaskAsync(taskName: string, options?: BackgroundTaskOptions | undefined) => Promise<void>

Register a named periodic background task.

ParamType
taskNamestring
optionsBackgroundTaskOptions

unregisterTaskAsync(...)

unregisterTaskAsync(taskName: string) => Promise<void>

Unregister a named periodic background task.

ParamType
taskNamestring

isTaskRegisteredAsync(...)

isTaskRegisteredAsync(taskName: string) => Promise<boolean>

Check whether a named task is registered.

ParamType
taskNamestring

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.

ParamType
listener(event: BackgroundTaskEvent) => void

Returns: Promise<PluginListenerHandle>


define(...)

define(callback: BackgroundTaskCallback) => void

React Native background-task compatible single-task define helper.

ParamType
callbackBackgroundTaskCallback

schedule(...)

schedule(options?: ReactNativeBackgroundTaskOptions | undefined) => Promise<void>

React Native background-task compatible single-task scheduler.

ParamType
optionsReactNativeBackgroundTaskOptions

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.

ParamType
resultBackgroundTaskResult

Interfaces

BackgroundTaskEvent

Payload emitted when native scheduling asks JavaScript to run a task.

PropTypeDescription
taskNamestringName passed to registerTaskAsync.
taskIdstringNative run identifier. The JavaScript wrapper finishes it automatically when the defined callback resolves.
timestampnumberNative timestamp for the run.
testbooleanTrue when triggered through triggerTaskWorkerForTestingAsync.

BackgroundTaskOptions

Options for registering a periodic background task.

PropTypeDescription
minimumIntervalnumberInexact 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.
requiresNetworkbooleanRequire an active network before running the native scheduler. Defaults to true.

PluginListenerHandle

PropType
remove() => Promise<void>

ReactNativeBackgroundTaskOptions

React Native background-task compatible schedule options.

PropTypeDescription
periodnumberDesired seconds between each execution. Mapped to minimumInterval minutes.
timeoutnumberAndroid-only timeout hint kept for API compatibility.

ReactNativeBackgroundTaskStatus

React Native background-task compatible status payload.

PropTypeDescription
availablebooleanWhether background tasks are available to the app.
unavailableReasonstringReason when unavailable.

Type Aliases

BackgroundTaskCallback

Function executed for a background task.

(event: BackgroundTaskEvent): void | BackgroundTaskResult | Promise<void | BackgroundTaskResult>

Enums

BackgroundTaskResult

MembersValueDescription
Success1The task finished successfully.
Failed2The task failed.

BackgroundTaskStatus

MembersValueDescription
Restricted1Background task scheduling is unavailable or restricted.
Available2Background task scheduling is available.

版本与发布记录

@capgo/capacitor-background-task 共发布 13 个版本,首次发布于 2026/05/12;过去 12 个月发布了 13 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.1.12latest2026/10/1525 天前
8.1.112026/10/1327 天前
8.1.102026/10/091 个月前
8.1.92026/10/081 个月前
8.1.82026/09/161 个月前
8.1.72026/07/113 个月前

关于 @capgo/capacitor-background-task 的常见问题

@capgo/capacitor-background-task 是什么?

Capacitor plugin for periodic background fetch tasks on iOS and Android.

如何安装 @capgo/capacitor-background-task?

在项目目录运行 npm install @capgo/capacitor-background-task,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capgo/capacitor-background-task 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@capgo/capacitor-background-task 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@capgo/capacitor-background-task 可以商用吗?

@capgo/capacitor-background-task 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@capgo/capacitor-background-task 的下载量有多少?

根据 npm 官方下载统计,@capgo/capacitor-background-task 在 2026/10/09 – 2026/11/07 这 30 天内被下载 40,293 次,日均约 1,343 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@capgo/capacitor-background-task 还在维护吗?

最新版本 8.1.12 发布于 2026/10/15(25 天前);至今共发布 13 个版本,其中过去 12 个月发布了 13 个;首次发布于 2026/05/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。