Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheduled NSTimer when app is in background?

How do people deal with a scheduled NSTimer when an app is in the background?

Let's say I update something in my app every hour.

updateTimer = [NSTimer scheduledTimerWithTimeInterval:60.0*60.0  target:self  selector:@selector(updateStuff)  userInfo:nil  repeats:YES]; 

When in the background, this timer obviously doesn't fire(?). What should happen when the user comes back to the app..? Is the timer still running, with the same times?

And what would would happen if the user comes back in over an hour. Will it trigger for all the times that it missed, or will it wait till the next update time?

What I would like it to do is update immediately after the app comes into the foreground, if the date it should have fired is in the past. Is that possible?

like image 398
cannyboy Avatar asked Dec 07 '11 13:12

cannyboy


People also ask

Does NSTimer run in background?

Problem is, NSTimer requires an active run loop which is not always readily available on background queues. The main thread has an active run loop but this defeats the purpose of having our timer run in the background so its a definite no go. So, to get a dedicated background-queue-friendly timer, we use GCD.

Will iOS terminate the app running in background after a specific time?

No, there is no specific time defined for this.


1 Answers

You shouldn't solve this problem by setting a timer, because you're not allowed to execute any code in the background. Imagine what will happen if the user restarts his iPhone in the meantime or with some other edge cases.

Use the applicationDidEnterBackground: and applicationWillEnterForeground: methods of your AppDelegate to get the behavior you want. It's way more robust, because it will also work when your App is completely killed because of a reboot or memory pressure.

You can save the time the timer will fire next when your App is going to the background and check if you should take action when the App comes back to the foreground. Also stop and start the timer in this methods. While your App is running you could use a timer to trigger the update at the right moment.

like image 97
Mac_Cain13 Avatar answered Sep 29 '22 12:09

Mac_Cain13