What is an NSTimer's behavior when the app is backgrounded?

前端 未结 2 1622
抹茶落季
抹茶落季 2021-01-18 13:07

I know that when you background an app, the timer stops running. However, what is the behavior when you come back from the background? Does the timer maintain its original <

相关标签:
2条回答
  • 2021-01-18 13:45

    You observed correctly how an NSTimer behaves.

    If you create a timer right now that should fire every ten minutes, it will try to fire ten minutes, 20 minutes, 30 minutes and so on from now. If the app goes to sleep after one minute and wakes up after 12 minutes, the timer will fire immediately, and then again at 20 minutes (not ten minutes after the timer firing, but 20 minutes after the original time).

    But if the timer misses one event completely and then is late for the next timer event as well, say if you wake up after 29 minutes, then the 10 minute event is dropped, the 20 minute event is fired as soon as possible (after 29 minutes), and the 30 minute event is fired after 30 minutes.

    0 讨论(0)
  • 2021-01-18 13:55

    You can't use timers for this problem. Here is what I discovered after investigating a similar problem:

    • After an app has been in the background for about 30 seconds, the timer stops.
    • When you re-enter from background the timer starts to fire again.

    What you can do to overcome this problem and add this functionality properly you would have to implement the timers on your backend server. Hit a service when the timer starts and start the timer when the app is in foreground. The timer will take care of itself but when app is terminated or in the background the server will come into play. Hit a service to get how much time has elapsed or send a push notification when the 10 minutes have passed.

    0 讨论(0)
提交回复
热议问题