Démarrage
Copiez un prompt de configuration avec les étapes d'installation et le 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 permet à une application Capacitor s'inscrire pour des tâches de synchronisation, de mise à jour de cache, de livraison d'analytiques et d'autres opérations de récupération de fond.
Installation
Section intitulée « Installation »npm install @capgo/capacitor-background-tasknpx cap syncConfiguration iOS
Section intitulée « Configuration iOS »Ajoutez le mode de traitement en arrière-plan et l'identifiant de tâche autorisé à ios/App/App/Info.plist:
<key>UIBackgroundModes</key><array> <string>processing</string></array><key>BGTaskSchedulerPermittedIdentifiers</key><array> <string>app.capgo.backgroundtask.processing</string></array>Exécutez ensuite :
npx 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éfinir l'appel de retour au niveau du module afin qu'il soit enregistré dès que l'application est démarré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; }});Enregistrer Le Planning
Section intitulée « Enregistrer Le Planning »Appeler registerTaskAsync après que votre application ait suffisamment de contexte pour activer le travail en arrière-plan.
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 session de test
Section intitulée « Déclencher une session de test »Utilisez le déclencheur de test en développement ou en QA. Il appelle toutes les tâches enregistrées immédiatement.
await BackgroundTask.triggerTaskWorkerForTestingAsync();Désinscrire une tâche
Section intitulée « Désinscrire une tâche »await BackgroundTask.unregisterTaskAsync(SYNC_TASK);Expiration de l'iOS
Section intitulée “Expiration de l'iOS”iOS peut interrompre une tâche de fond avant que votre travail JavaScript ne soit terminé. Écoutez les événements d'expiration lorsque la suppression ou la mise à jour des points de contrôle est importante.
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 de React Native
Section intitulée “Compatibilité de la tâche de fond de React Native”Le plugin expose également une petite couche de compatibilité pour les applications migrantes 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 de fond est opportuniste, pas exacte.
- Gardez vos travaux courts et idempotents.
- Sauvegardez tout l'état dont vous avez besoin avant de revenir
BackgroundTaskResult.Success. - Évitez de vous appuyer sur des tâches de fond pour les échéances ou les alarmes visibles par l'utilisateur.