Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Notifications and Background Tasks

Background Tasks and Background Work

Run code when your Expo app is not on screen: defineTask with expo-task-manager, expo-background-task, location and notification tasks, OS limits and how to design for them.

Sometimes your app has work to do when nobody is looking at it: sync new data overnight, upload a photo after the user left the screen, record a run's GPS track, react to a silent push. Mobile operating systems are strict about this. They protect battery life, so they decide if and when your code may run.

Expo exposes background work through expo-task-manager, which lets you define named tasks, plus modules that trigger them: expo-background-task (periodic work), expo-location (location updates) and expo-notifications (background notifications).

What runs on this site. Background execution is controlled by iOS and Android, so the real code is read-only. The runnable stand-in is a small task manager in Node.js that shows the structure (define once, register, the system calls you) and the rules (a minimum interval, a time budget).

The rule that shapes everything

You do not control background execution. You request it, and the OS decides. Expect:

  • Periodic work runs about as often as you ask for, never faster than the OS minimum (typically 15 minutes or more) and sometimes much less often, depending on battery, usage and network.
  • Each run has a short time budget (roughly 30 seconds on iOS, similar on Android). Do a little work and finish.
  • If the user force-quits the app on iOS, background work generally stops until they open it again.
  • Nothing is guaranteed, so never depend on a background task for correctness. Treat it as an optimization and make the app sync correctly when opened.

Defining a task

A task is defined at the top level of your code (outside components), so it exists even when the app is started in the background with no UI.

JSX
// background-sync.js
import * as TaskManager from 'expo-task-manager';
import * as BackgroundTask from 'expo-background-task';

export const SYNC_TASK = 'sync-notes';

TaskManager.defineTask(SYNC_TASK, async () => {
  try {
    await syncNotesWithServer();         // keep it short
    return BackgroundTask.BackgroundTaskResult.Success;
  } catch (e) {
    return BackgroundTask.BackgroundTaskResult.Failed;
  }
});

export async function registerSync() {
  const status = await BackgroundTask.getStatusAsync();
  if (status === BackgroundTask.BackgroundTaskStatus.Restricted) return; // user disabled it

  if (!(await TaskManager.isTaskRegisteredAsync(SYNC_TASK))) {
    await BackgroundTask.registerTaskAsync(SYNC_TASK, { minimumInterval: 60 }); // minutes
  }
}

Import this file from your root layout so defineTask runs at startup. Then call registerSync() once, for example after login. To stop: BackgroundTask.unregisterTaskAsync(SYNC_TASK).

expo-background-task replaces the older expo-background-fetch. It uses WorkManager on Android and BGTaskScheduler on iOS, which is the modern, battery-friendly route. In development you can trigger a run immediately with BackgroundTask.triggerTaskWorkerForTestingAsync().

What the stand-in shows

Node.js A task manager that obeys OS rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output: the 20 minute wake-up skips both tasks (not due yet), and the slow task is cut off by the time budget. That is exactly how a real device behaves.

Other background triggers

Location. expo-location can deliver updates while the app is in the background:

JSX
TaskManager.defineTask('track-run', ({ data, error }) => {
  if (error) return;
  const { locations } = data;
  saveToDatabase(locations);
});

await Location.requestForegroundPermissionsAsync();
await Location.requestBackgroundPermissionsAsync();
await Location.startLocationUpdatesAsync('track-run', {
  accuracy: Location.Accuracy.Balanced,
  foregroundService: { notificationTitle: 'Recording run', notificationBody: 'Tracking your route' },
});

Background location needs the "always" permission, a clear explanation to the user, UIBackgroundModes and Android manifest entries (set by the expo-location config plugin), and store review justification. Use it only when the feature truly needs it.

Notifications. A silent push ("_contentAvailable": true for iOS, a data-only message for Android) can wake your app to process data. Register it with Notifications.registerTaskAsync(TASK) and handle it in a defineTask. It is also best effort.

Long operations in the foreground. If the user starts a big upload and then switches apps, ask for a bit more time with the library you use (for example expo-file-system's createUploadTask/createDownloadTask support background sessions on iOS).

Designing for unreliable background work

flowchart TD
  A["App opens"] --> B["Sync on foreground<br/>(always correct)"]
  C["Background task runs"] --> D["Small, idempotent sync<br/>(nice to have)"]
  B --> E["Local database"]
  D --> E

The foreground sync guarantees correctness. The background task only makes it faster.

Rules that keep you safe:

  1. Idempotent: running the task twice must not duplicate data.
  2. Short: fetch a small delta (changes since a timestamp), not everything.
  3. Resumable: store progress so a cut-off run can continue next time.
  4. Quiet: do not show a notification for every background run.
  5. Respect the user: if status is Restricted (Low Power Mode, background refresh disabled), do not nag.
Node.js An idempotent delta sync

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Testing background tasks

  • Use a development build on a device; Expo Go does not support most background features.
  • Call triggerTaskWorkerForTestingAsync() (background task) to run the task now.
  • On iOS you can also pause in Xcode and use the e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"..."] debugger command.
  • On Android use adb shell cmd jobscheduler run or WorkManager's test tools.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Who decides when a background task runs?

    You only request background work. The OS schedules it and may delay or skip it.
  2. 2. Where must TaskManager.defineTask be called?

    The app may start headless in the background, so the task must be defined without any UI.
  3. 3. Why should background sync be idempotent?

    Retries and interruptions are normal, so repeating a run must not duplicate data.
  4. 4. Which package replaces expo-background-fetch for periodic work?

    expo-background-task uses the modern platform schedulers.

Summary

  • Background work is requested, not controlled: the OS decides when and for how long.
  • Define tasks at module top level with TaskManager.defineTask, register with expo-background-task.
  • Location and silent-push tasks use the same defineTask mechanism.
  • Design for short, idempotent, resumable work and always sync again on app open.
  • Test on a development build with the trigger helper.

Next: EAS Build profiles