Running Periodic Background Fetch in Expo with Task Manager
Learn how to schedule reliable background network calls in Expo using the Task Manager API, keeping data fresh even when the app is closed.
Insight
Expo’s TaskManager lets you define headless tasks that run even when the UI is not active. Pair it with expo-background-fetch to schedule periodic network syncs, ideal for push‑enabled news feeds or token refreshes. The system respects OS power policies, so you should keep the task lightweight and idempotent.
Example
import * as TaskManager from 'expo-task-manager';
import * as BackgroundFetch from 'expo-background-fetch';
const FETCH_TASK = 'background-fetch-sync';
TaskManager.defineTask(FETCH_TASK, async () => {
try {
const res = await fetch('https://api.example.com/sync');
const data = await res.json();
// store data locally, e.g., using MMKV or AsyncStorage
return BackgroundFetch.Result.NewData;
} catch {
return BackgroundFetch.Result.Failed;
}
});
await BackgroundFetch.registerTaskAsync(FETCH_TASK, {
minimumInterval: 15 * 60, // 15 minutes
stopOnTerminate: false,
startOnBoot: true,
});
Takeaway
Schedule background fetches with a short interval and keep the work minimal; heavy processing should be deferred to when the app is foregrounded. This pattern ensures your app stays up‑to‑date without draining battery.