user3072558
user3072558

Reputation: 723

NSTimer behavior on background/foreground

Scenario is:

Application has on main run loop that runs every 5 min. When app is backgrounded, the timer is not invalidated.

On foreground after waiting a bit (say 10 min), the timer immediately fires twice. I'm unclear as to what the defined behavior here should be (if any) other than on background, the timer is paused/suspended along with the app.

It seems to me that when the app is foregrounded, the timer actually looks at the elapsed time since background, determines the number of times it should have fired in between, and fires them all. I observed this scenario happening both on iOS 7 simulator and iOS 7 iphone.

Google search didn't turn up much info on this topic. Any ideas/pointers?

Update: Clarification - my question is what is the behavior for NSTimer when the application is backgrounded and then foregrounded again, assuming the timer is not invalidated/nil-ed on background, and a new timer is not created on foreground.

Code sample (code is bit old - pre ARC days):

@implementation ReportHandler {
    NSTimer *_reportTimer;
}

- (id)init
{
    if (_reportTimer == nil) {
        _reportTimer = [[NSTimer  timerWithTimeInterval:5*60 target:self selector:@selector(didFireReportTimer:) userInfo:nil repeats:YES] retain];
        [[NSRunLoop mainRunLoop] addTimer:_reportTimer forMode:NSDefaultRunLoopMode];
    }
}

- (void)didFireReportTimer:(NSTimer *)timer {
   // send report over network here, timer is not invalidated here
}

There are no background/foreground handlers either here or in the app delegate dealing with this timer.

Upvotes: 4

Views: 3032

Answers (1)

jmah
jmah

Reputation: 2214

It seems to me that when the app is foregrounded, the timer actually looks at the elapsed time since background, determines the number of times it should have fired in between, and fires them all. I observed this scenario happening both on iOS 7 simulator and iOS 7 iphone.

That is a correct description of the behavior of NSTimer and the run loop. When your app is suspended it won't fire (by default, when you background it; but if you start a background task, it will fire as normal while the task is running).

Upvotes: 2

Related Questions