4

I need to be able to program background tasks. Little "crons" if you will, that execute some simple code. While not being an expert in GCD I was wondering:

  1. What is the maximum time I expect for the background task to actually perform its duties in the background before apps quits completely

  2. Can I "program" multiple tasks and expect them to complete in timely order

  3. Are they only active as long as the app is launched? ( I bet they are, unlike local notifications that dont really care whether the app is running in the background or not, so just asking to be sure)

  4. How to I keep track of them and cancel if needed?

    For instance I able to do something like this and task is performed. I went as far as 1 minute here and it works.

    let backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
    DispatchQueue.main.asyncAfter(wallDeadline: DispatchWallTime.now() + 60) {
                // Some action here
                UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
    })
    
Community
  • 1
  • 1
kernelpanic
  • 2,876
  • 3
  • 34
  • 58
  • Possible duplicate of [How long does Apple permit a background task to run?](http://stackoverflow.com/questions/28275415/how-long-does-apple-permit-a-background-task-to-run) –  Apr 02 '17 at 19:23
  • Marked as a duplicate, I know you have several questions, but before you post multiple questions you should search for them individually and exclude the duplicates. When you do , edit your question and hit me up I will remove the duplicate flag. –  Apr 02 '17 at 19:24

1 Answers1

0

You can print the time remaining for a given session using backgroundTimeRemaining (docs here). Apple makes no guarantees about what this time will be, it varies with battery level, hardware, resources, etc., so probably no good for a long running persistent background task. You might want to consider the background fetch API, although this is similarly throttled by iOS and you don't have complete control over when it runs.

Tim Johnsen
  • 1,471
  • 14
  • 33