Scheduled NSTimer when app is in background?

cannyboy picture cannyboy · Dec 7, 2011 · Viewed 69.3k times · Source

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?

Answer

Robert picture Robert · Jul 3, 2013

You can have a timer fire while in background execution mode. There are a couple of tricks:

If you are on the main thread:

{
    // Declare the start of a background task
    // If you do not do this then the mainRunLoop will stop
    // firing when the application enters the background
    self.backgroundTaskIdentifier =
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{

        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
    }];

    // Make sure you end the background task when you no longer need background execution:
    // [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];

    [NSTimer scheduledTimerWithTimeInterval:0.5
                                     target:self
                                   selector:@selector(timerDidFire:)
                                   userInfo:nil
                                    repeats:YES];
}

- (void) timerDidFire:(NSTimer *)timer
{
    // This method might be called when the application is in the background.
    // Ensure you do not do anything that will trigger the GPU (e.g. animations)
    // See: http://developer.apple.com/library/ios/DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW47
}

Notes

  • Apps only get ~ 10 mins (~3 mins as of iOS 7) of background execution - after this the timer will stop firing.
  • As of iOS 7 when the device is locked it will suspend the foreground app almost instantly. The timer will not fire after an iOS 7 app is locked.