---
title: "backgroundTask(_:action:)"
framework: swiftui
role: symbol
role_heading: Instance Method
path: "swiftui/scene/backgroundtask(_:action:)"
---

# backgroundTask(_:action:)

Runs the specified action when the system provides a background task.

## Declaration

```swift
nonisolated func backgroundTask<D, R>(_ task: BackgroundTask<D, R>, action: @escaping @Sendable (D) async -> R) -> some Scene where D : Sendable, R : Sendable

```

## Parameters

- `task`: The type of task with which to associate the provided action.
- `action`: An async closure that the system runs for the specified task type.

## Discussion

Discussion When the system wakes your app or extension for one or more background tasks, it will call any actions associated with matching tasks. When your async actions return, the system put your app back into a suspended state. The system considers the task completed when the action closure that you provide returns. If the action closure has not returned when the task runs out of time to complete, the system cancels the task. Use withTaskCancellationHandler(operation:onCancel:isolation:) to observe whether the task is low on runtime. /// An example of a Weather Application. struct WeatherApp: App {     var body: some Scene {         WindowGroup {             Text("Responds to App Refresh")         }         .backgroundTask(.appRefresh("WEATHER_DATA")) {             await updateWeatherData()         }     }     func updateWeatherData() async {         // fetches new weather data and updates app state     } }

## See Also

### Handling background tasks

- [BackgroundTask](swiftui/backgroundtask.md)
- [SnapshotData](swiftui/snapshotdata.md)
- [SnapshotResponse](swiftui/snapshotresponse.md)
