BGTaskScheduler: Is it possible to schedule a background task inside a background task?

Viewed 83

Let's say an app has a background task to execute after 1 hour, but when it executes, it discovers that the user has no internet connection, so it cannot do its job. Is it possible to schedule another background task inside the background task to execute after another hour?

1 Answers

Yes, you can schedule the next task when processing the current task.

The code example in Using Background Tasks to Update Your App does precisely that, scheduling the next task (scheduleAppRefresh) as the first step in handling an app refresh:

func handleAppRefresh(task: BGAppRefreshTask) {
    // Schedule a new refresh task.
    scheduleAppRefresh()

    // Create an operation that performs the main part of the background task.
    let operation = RefreshAppContentsOperation()
   
    // Provide the background task with an expiration handler that cancels the operation.
    task.expirationHandler = {
        operation.cancel()
    }

    // Inform the system that the background task is complete
    // when the operation completes.
    operation.completionBlock = {
        task.setTaskCompleted(success: !operation.isCancelled)
    }

    // Start the operation.
    operationQueue.addOperation(operation)
}

Also see Refreshing and Maintaining Your App Using Background Tasks sample project.

Related