Scheduled NSTimer when app is in background?

IphoneIosNstimerUiapplicationdelegate

Iphone Problem Overview


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?

Iphone Solutions


Solution 1 - Iphone

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.

Solution 2 - Iphone

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.

Solution 3 - Iphone

In case you or someone else is looking for how to run the NSTimer in the background in Swift, add the following to your App Delegate:

var backgroundUpdateTask: UIBackgroundTaskIdentifier = 0


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    return true
}

func applicationWillResignActive(application: UIApplication) {
    self.backgroundUpdateTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
        self.endBackgroundUpdateTask()
    })
}

func endBackgroundUpdateTask() {
    UIApplication.sharedApplication().endBackgroundTask(self.backgroundUpdateTask)
    self.backgroundUpdateTask = UIBackgroundTaskInvalid
}

func applicationWillEnterForeground(application: UIApplication) {
    self.endBackgroundUpdateTask()
}

Cheers!

Solution 4 - Iphone

> When in the background, this timer obviously doesn't fire

This post suggests that things aren't quite as clear as that. You should invalidate your timers as your app goes into the background and restart them when it comes back to foreground. Running stuff while in the background might be possible but then again it might get you killed...

You can find good documentation about the iOS multitasking approach here.

Solution 5 - Iphone

On iOS 8 you can get your NSTimer working when the app is in background (even if iphone is locked) up to ~3mins in a simple way:

just implement scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: method as usual, where you need. Inside AppDelegate create a property:

UIBackgroundTaskIdentifier backgroundUpdateTask

then in your appDelegate methods:

- (void)applicationWillResignActive:(UIApplication *)application {
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
    [self endBackgroundUpdateTask];
    }];
}

- (void) endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [self endBackgroundUpdateTask];
}

after 3 mins the timer will not fire more, when the app will comeback in foreground it will start to fire again

Solution 6 - Iphone

You need to add your timer in current run loop.

[[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSRunLoopCommonModes];

Solution 7 - Iphone

[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    loop = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(Update) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:loop forMode:NSRunLoopCommonModes];

Solution 8 - Iphone

You need to add timer in Run loop (Reference - Apple developer page for Run loop understanding).

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self
selector:@selector(updateTimer)  userInfo:nil  repeats:true];

[[NSRunLoop mainRunLoop] addTimer: timer forMode:NSRunLoopCommonModes];

//funcation

-(void) updateTimer{
NSLog(@"Timer update");

}

You need to add permission (Required background modes) of Background working in infoPlist.

Solution 9 - Iphone

create Global uibackground task identifier.

UIBackgroundTaskIdentifier bgRideTimerTask;

now create your timer and add BGTaskIdentifier With it, Dont forget to remove old BGTaskIdentifier while creating new Timer Object.

 [timerForRideTime invalidate];
 timerForRideTime = nil;
                            
 bgRideTimerTask = UIBackgroundTaskInvalid;
                            
 UIApplication *sharedApp = [UIApplication sharedApplication];       
 bgRideTimerTask = [sharedApp beginBackgroundTaskWithExpirationHandler:^{
                                
                            }];
 timerForRideTime =  [NSTimer scheduledTimerWithTimeInterval:1.0
                                                                                 target:self
                                                                               selector:@selector(timerTicked:)
                                                                               userInfo:nil
                                                                                repeats:YES]; 
                                                   [[NSRunLoop currentRunLoop]addTimer:timerForRideTime forMode: UITrackingRunLoopMode];

Here this will work for me even when app goes in background.ask me if you found new problems.

Solution 10 - Iphone

For me, The background task and run loop was critical and not accurate most of the time.

I decided to use UserDefault approach.

Step 1: Add app enter background/foreground observers

Step 2: When user goes to background, store timer's time in user default with current timestamp

Step 3: When user comes to foreground, compare user default timestamp with current timestamp, and calculate your new timer

All done.

Code snippet:

// Add in viewDidLoad/init functions

NotificationCenter.default.addObserver(self, selector: #selector(self.background(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.foreground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)

// Add in your VC/View

let userDefault = UserDefaults.standard

@objc func background(_ notification: Notification) {
    userDefault.setValue(timeLeft, forKey: "OTPTimer")
    userDefault.setValue(Date().timeIntervalSince1970, forKey: "OTPTimeStamp")
}

@objc func foreground(_ notification: Notification) {
    let timerValue: TimeInterval = userDefault.value(forKey: "OTPTimer") as? TimeInterval ?? 0
    let otpTimeStamp = userDefault.value(forKey: "OTPTimeStamp") as? TimeInterval ?? 0
    let timeDiff = Date().timeIntervalSince1970 - otpTimeStamp
    let timeLeft = timerValue - timeDiff
    completion((timeLeft > 0) ? timeLeft : 0)
    print("timeLeft:", timeLeft) // <- This is what you need
}

Solution 11 - Iphone

Swift 4+ version of gellieb's answer

var backgroundUpdateTask: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier(rawValue: 0)


func applicationWillResignActive(_ application: UIApplication) {
    self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
        self.endBackgroundUpdateTask()
    })
}
func endBackgroundUpdateTask() {
    UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
    self.backgroundUpdateTask = UIBackgroundTaskIdentifier.invalid
}

func applicationWillEnterForeground(application: UIApplication) {
    self.endBackgroundUpdateTask()
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncannyboyView Question on Stackoverflow
Solution 1 - IphoneMac_Cain13View Answer on Stackoverflow
Solution 2 - IphoneRobertView Answer on Stackoverflow
Solution 3 - IphonegelliebView Answer on Stackoverflow
Solution 4 - Iphonejbat100View Answer on Stackoverflow
Solution 5 - IphoneEnrico CupelliniView Answer on Stackoverflow
Solution 6 - IphoneMaverick KingView Answer on Stackoverflow
Solution 7 - IphonevualoaithuView Answer on Stackoverflow
Solution 8 - IphoneM Abubaker MajeedView Answer on Stackoverflow
Solution 9 - IphoneNIRAV BHAVSARView Answer on Stackoverflow
Solution 10 - IphoneMohammad Zaid PathanView Answer on Stackoverflow
Solution 11 - IphoneMutaweView Answer on Stackoverflow