<!--
{
  "availability" : [
    "iOS: 16.0.0 -",
    "iPadOS: 16.0.0 -",
    "macCatalyst: 16.0.0 -",
    "macOS: 13.0.0 -",
    "tvOS: 16.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 9.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "SwiftUI",
  "identifier" : "/documentation/SwiftUI/Scene/backgroundTask(_:action:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "SwiftUI"
    ],
    "preciseIdentifier" : "s:7SwiftUI5ScenePAAE14backgroundTask_6actionQrAA010BackgroundE0Vyqd__qd_0_G_qd_0_qd__YaYbcts8SendableRd__sAIRd_0_r0_lF"
  },
  "title" : "backgroundTask(_:action:)"
}
-->

# backgroundTask(_:action:)

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

```
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

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
<doc://com.apple.documentation/documentation/Swift/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
    }
}
```

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)