Command palette

@yasinsensoy/native

React Native · APIs and utilities

Background tasks

Background tasks.

7 exports

Import

import { BackgroundTask } from "@yasinsensoy/native";

Background tasks. Define the handler in the app's root file (index.js, outside components): when the app is started in the background it runs without rendering the screen.

NameTypeDescription
define(name: string, handler: BackgroundTaskHandler) => voidDefines a task handler. Defining again with the same name replaces the previous one.
defined() => string[]Defined task names.
schedule(name: string, options?: BackgroundScheduleOptions) => Promise<void>Runs the task periodically. On Android it survives device restarts. On iOS the task name must be in the ui.config background.tasks list; the simulator does not support it (E_BACKGROUND).
cancel(name: string) => Promise<void>Removes the schedule.
getScheduled() => Promise<ScheduledBackgroundTask[]>Scheduled tasks.
runNow(name: string) => Promise<void>Runs the task now (for testing). On Android it goes through the real background path (JobScheduler + headless JS).
status() => Promise<BackgroundStatus>Background execution permission (iOS: Settings > Background App Refresh).

Why the task is running.

type BackgroundReason = "scheduled" | "boot" | "manual"

What the task handler receives.

NameTypeDescription
namestringTask name.
reasonBackgroundReasonWhy the task runs.
expiredbooleanBecomes true when the time iOS granted runs out; stop long work here.

Task handler; the task ends when the returned Promise settles.

type BackgroundTaskHandler = (context: BackgroundTaskContext) => Promise<void> | void

Options for BackgroundTask.schedule.

NameTypeDefaultDescription
interval?number15Minimum interval (minutes, at least 15). The system may delay it based on battery and usage; exact timing is not guaranteed.
network?"none" | "any" | "unmetered""none"Network condition: any any connection, unmetered Wi-Fi.
charging?booleanfalseOnly while charging.
startOnBoot?booleanfalseAndroid: also run right away when the device boots and when the app is updated (even if the app is not opened). No equivalent on iOS.

Scheduled task.

NameTypeDescription
namestringTask name.
intervalnumberMinimum interval between runs (minutes).
networkstring | nullRequired network type; null if none is required.
chargingbooleanRuns only while charging.
startOnBootbooleanScheduled again after the device restarts.
pendingbooleanWhether it is pending in the system.

Can it run in the background: the iOS user setting (Background App Refresh); unavailable on the iOS simulator. Always available on Android.

type BackgroundStatus = "available" | "denied" | "restricted" | "unavailable"