跳过内容

开始

GitHub

@capgo/capacitor-background-task 让一个 Capacitor 应用程序注册周期性任务、缓存刷新、分析数据传递和其他后台抓取操作.

您可以使用我们的 AI-Assisted Setup 来安装插件。使用以下命令将 Capgo 技能添加到您的 AI 工具中:

终端窗口
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

然后使用以下提示:

Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-background-task` plugin in my project.

如果您prefer Manual Setup,安装插件并运行以下命令,然后遵循以下平台特定的说明:

终端窗口
npm install @capgo/capacitor-background-task
npx cap sync

添加背景处理模式和允许的任务标识符 ios/App/App/Info.plist:

<key>UIBackgroundModes</key>
<array>
<string>processing</string>
</array>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>app.capgo.backgroundtask.processing</string>
</array>

然后运行:

终端窗口
npx cap sync ios
import { BackgroundTask, BackgroundTaskResult } from '@capgo/capacitor-background-task';

复制到剪贴板

import { BackgroundTask, BackgroundTaskResult } from '@capgo/capacitor-background-task';
const SYNC_TASK = 'sync-offline-data';
BackgroundTask.defineTask(SYNC_TASK, async () => {
try {
await fetch('https://api.example.com/sync', { method: 'POST' });
return BackgroundTaskResult.Success;
} catch {
return BackgroundTaskResult.Failed;
}
});

导入部分:导入Capgo模块并使用它来定义任务。

Section titled “注册调度表”

Call registerTaskAsync 在您的应用程序有足够的上下文后,启用后台作业。

await BackgroundTask.registerTaskAsync(SYNC_TASK, {
minimumInterval: 30,
requiresNetwork: true,
});

minimumInterval 时间单位为分钟。Android强制执行最小 15 分钟。iOS 将该值视为最早开始日期并可能稍后运行。

const status = await BackgroundTask.getStatusAsync();
const isRegistered = await BackgroundTask.isTaskRegisteredAsync(SYNC_TASK);
const registeredTasks = await BackgroundTask.getRegisteredTasksAsync();
console.log({ status, isRegistered, registeredTasks });

在开发或 QA 环境中使用测试触发器。它会立即调用所有已注册的任务。

await BackgroundTask.triggerTaskWorkerForTestingAsync();

注销一个任务

标题:注销一个任务
await BackgroundTask.unregisterTaskAsync(SYNC_TASK);

iOS可以在JavaScript工作完成之前停止一个后台任务。请在清理或检查点时监听失效事件。

const expiration = await BackgroundTask.addExpirationListener((event) => {
console.warn('Background task expired', event.taskName, event.taskId);
});
await expiration.remove();

React Native后台任务兼容性

标题:React Native后台任务兼容性

插件还暴露了一个用于从 react-native-background-task.

import { BackgroundTask } from '@capgo/capacitor-background-task';
BackgroundTask.define(async () => {
await fetch('https://api.example.com/sync', { method: 'POST' });
});
await BackgroundTask.schedule({
period: 1800,
});

生产说明

生产注意事项
  • 后台调度是机会主义的,而不是精确的。
  • 保持工作短暂且幂等。
  • 在返回之前持久化您需要的任何状态。 BackgroundTaskResult.Success.
  • 避免依赖后台任务来实现用户可见的截止日期或闹钟。

继续从 Getting Started

继续从 Getting Started

如果您正在使用 Getting Started 来规划原生插件工作,连接它与 使用 @capgo/capacitor-background-task 为原生能力在使用 @capgo/capacitor-background-task, Capgo 插件目录 在 Capgo 插件目录中为产品工作流程 Capacitor 由 Capgo 提供的插件 在 Capacitor 由 Capgo 提供的插件中实现详细信息 添加或更新插件 在添加或更新插件中实现详细信息 Ionic Enterprise 插件替代方案 在 Ionic Enterprise 插件替代方案中为产品工作流程