Background Tasks (iOS)
Also known as: bgtaskscheduler, ios background tasks, ios background tasks
iOS Background Tasks are system-scheduled windows, managed by the BackgroundTasks framework, in which an app can run short maintenance or longer processing work while it is not on screen. iOS decides when they run based on usage, battery, and charging state.
- Two task types: BGAppRefreshTask (short) and BGProcessingTask (long, can require power/network).
- Identifiers must be listed in BGTaskSchedulerPermittedIdentifiers and registered at launch.
- iOS chooses run timing from usage, battery, and charging state; tasks must set an expirationHandler.
The BackgroundTasks framework
Since iOS 13, apps schedule deferred work through the BackgroundTasks framework. It offers two request types: BGAppRefreshTask for short, frequent updates (typically tens of seconds), and BGProcessingTask for longer, heavier work such as cleanup, indexing, or database maintenance, which can optionally require external power or network.
You register a launch handler for each task identifier in application(_:didFinishLaunchingWithOptions:) using BGTaskScheduler.shared.register(...), list those identifiers under BGTaskSchedulerPermittedIdentifiers in `Info.plist`, and enable the Background processing / Background fetch capabilities. The system, not the app, decides when each submitted BGTaskRequest actually runs.
Constraints and the expiration handler
iOS budgets background execution heavily. Run frequency adapts to how often you open the app, the device's battery level, Low Power Mode, and whether it is charging, so there is no guaranteed schedule. BGProcessingTask jobs are more likely to run while the device is charging and idle overnight.
Every task must set an expirationHandler and call setTaskCompleted(success:) when done. If you overrun the granted time, iOS invokes the expiration handler so you can save state and exit cleanly; ignoring it risks the system terminating the app and throttling future scheduling.
Why a cleaner uses it
Scanning the photo library for duplicates and similar shots through PhotoKit is exactly the kind of CPU-and-IO-heavy job that suits a BGProcessingTask. Cleanor can quietly pre-compute hashes and refresh its duplicate index overnight while charging, so that when you open the app the results are ready immediately instead of forcing you to wait for a fresh scan.