Home > Software design >  BGTaskScheduler: Is it possible to schedule a background task inside a background task?
BGTaskScheduler: Is it possible to schedule a background task inside a background task?

Time:07-27

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?

CodePudding user response:

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.

CodePudding user response:

I think I found the answer to my question. BGTaskScheduler.shared.register can only be executed in applicationDidFinishLaunching(_:) as per documentation docs here,

which means that I cannot simply register another task inside of the bgtask. This new task has to be registered first in applicationDidFinishLaunching(_:), which I am assuming is unavailable during the background task launch sequence, as the BGTask purpose is to execute predefined segments of code.

  • Related