Essai gratuit de 14 jours sans carte de crédit
Copiez un prompt de configuration avec les étapes d'installation et la guide markdown complet pour ce plugin.
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-background-task`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/docs/plugins/background-task/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
@capgo/capacitor-background-task lets a Capacitor app register named periodic jobs for sync, cache refreshes, analytics delivery, and other background fetch operations.
Installer
Section intitulée « Installer »Vous pouvez utiliser notre Setup assisté par l'IA pour installer le plugin. Ajoutez les compétences Capgo à votre outil d'IA en utilisant la commande suivante :
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-pluginsUtilisez ensuite la commande suivante :
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-background-task` plugin in my project.Si vous préférez la mise en place manuelle, installez le plugin en exécutant les commandes suivantes et suivez les instructions spécifiques à la plateforme ci-dessous.
bun add @capgo/capacitor-background-taskbunx cap syncConfiguration iOS
Section intitulée « Configuration iOS »Ajoutez le mode de traitement en arrière-plan et l'identifiant de la tâche autorisée ios/App/App/Info.plist:
<key>UIBackgroundModes</key><array> <string>processing</string></array><key>BGTaskSchedulerPermittedIdentifiers</key><array> <string>app.capgo.backgroundtask.processing</string></array>Then run:
bunx cap sync iosImporter
Section intitulée « Importer »import { BackgroundTask, BackgroundTaskResult } from '@capgo/capacitor-background-task';Définir une tâche
Section intitulée « Définir une tâche »Définissez l'appel de rappel au niveau du module afin qu'il soit enregistré dès que l'application est lancée par le système d'exploitation.
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; }});Inscrire La Planification
Section intitulée « Inscrire La Planification »Appeler registerTaskAsync after your app has enough context to enable the background job.
await BackgroundTask.registerTaskAsync(SYNC_TASK, { minimumInterval: 30, requiresNetwork: true,});minimumInterval est en minutes. Android impose un minimum de 15 minutes. iOS traite la valeur comme une date de début la plus tôt et peut exécuter plus tard.
Vérifier l'état
Section intitulée « Vérifier l'état »const status = await BackgroundTask.getStatusAsync();const isRegistered = await BackgroundTask.isTaskRegisteredAsync(SYNC_TASK);const registeredTasks = await BackgroundTask.getRegisteredTasksAsync();
console.log({ status, isRegistered, registeredTasks });Déclencher une épreuve
Section intitulée « Déclencher une épreuve »Utilisez le déclencheur d'essai en développement ou en QA. Il appelle immédiatement chaque tâche enregistrée.
await BackgroundTask.triggerTaskWorkerForTestingAsync();Désinscrire une tâche
Section intitulée « Désinscrire une tâche »await BackgroundTask.unregisterTaskAsync(SYNC_TASK);Expiration sur iOS
Section intitulée « Expiration sur iOS »iOS peut interrompre une tâche de fond avant que votre travail JavaScript ne soit terminé. Écoutez les événements d'expiration lorsqu'il s'agit de nettoyage ou de point de contrôle.
const expiration = await BackgroundTask.addExpirationListener((event) => { console.warn('Background task expired', event.taskName, event.taskId);});
await expiration.remove();Compatibilité de la tâche de fond React Native
Section intitulée « Compatibilité de la tâche de fond React Native »La plugin expose également une petite couche de compatibilité pour les applications en cours de migration de 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,});Notes de production
Section intitulée « Notes de production »- La planification en arrière-plan est opportuniste, pas précise.
- Conservez vos travaux courts et idempotents.
- Enregistrez tout l'état dont vous avez besoin avant de renvoyer.
BackgroundTaskResult.Success. - Évitez de vous fier aux tâches de fond pour les échéances ou les alarmes visibles par l'utilisateur.
Continuez de Getting Started.
Section intitulée “Continuez de Getting Started”.Si vous utilisez Getting Started pour planifier le travail de plugin natif, connectez-l’avec Utilisez @capgo/capacitor-tâche de fond pour la capacité native dans Utilisez @capgo/capacitor-tâche de fond, Capgo Répertoire de plugin pour le flux de travail du produit dans Capgo Répertoire de plugin, Capacitor Plugins par Capgo pour les détails d'implémentation dans Capacitor Plugins par Capgo Ajouter ou mettre à jour les plugins pour les détails d'implémentation dans Ajouter ou mettre à jour les plugins, et Alternatives de plugins Ionic Enterprise pour le flux de travail du produit dans Alternatives de plugins Ionic Enterprise.