1

What happens if I call beginBackgroundTaskWithExpirationHandler periodically every few minutes and never call endBackgroundTask?

Is there any limit for creating background tasks?

jscs
  • 63,694
  • 13
  • 151
  • 195
  • Depends on whether your app is in the foreground or not at the time. – rmaddy Feb 18 '17 at 22:44
  • 1
    @rmaddy what if app always in background? –  Feb 18 '17 at 22:49
  • 1
    If the app in been kept alive in the background with this mechanism and you neglect to call `endBackgroundTask`, the OS will kill your app (rather than just gracefully suspending it). So you generally want to call `endBackgroundTask`, even if you're only doing this in the timeout block. – Rob Feb 18 '17 at 22:56
  • By the way, if your intention in calling this "every few minutes" is to keep the app running perpetually in the background, that will not work. – Rob Feb 18 '17 at 22:59

1 Answers1

4

What happens if i call beginBackgroundTaskWithExpirationHandler periodically every minutes and never call endBackgroundTask

  • Nothing happens. Despite its name, beginBackgroundTaskWithExpirationHandler: does not actually "begin" a task. It might be better thought of as "register..." rather than "begin...." You're just telling the system that you're in the middle of doing something that would like to complete if that's ok.

is there any limit for creating background task?

  • No. However, apps running background tasks have a finite amount of time in which to run them. (You can find out how much time is available using the backgroundTimeRemaining property.) If you do not call endBackgroundTask: for each task before time expires, the system kills the app. If you provide a block object in the handler parameter, the system calls your handler before time expires to give you a chance to end the task.

This and this are good reads on the topic.

Community
  • 1
  • 1
ystack
  • 1,785
  • 12
  • 23
  • what if my task should has more time to execute , i mean is there any way to reset expiration time by checking location or something else? –  Feb 20 '17 at 19:07
  • Yes, apps that initiate downloads in the foreground can hand off management of those downloads to the system, thereby allowing the app to be suspended or terminated while the download continues. This would help you implement it => https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html – ystack Feb 20 '17 at 19:14
  • What happens if you register a newTask inside the expirationHandler? Would you get more until the OS gets tired of you? Or it would just fail silently? – mfaani Aug 01 '17 at 18:36