How do I create a NSTimer on a background thread?

AWF4vk picture AWF4vk · Nov 29, 2011 · Viewed 65.1k times · Source

I have a task that needs to be performed every 1 second. Currently I have an NSTimer firing repeatedly every 1 sec. How do I have the timer fire in a background thread (non UI-thread)?

I could have the NSTimer fire on the main thread then use NSBlockOperation to dispatch a background thread, but I'm wondering if there is a more efficient way of doing this.

Answer

Marius picture Marius · Aug 29, 2012

If you need this so timers still run when you scroll your views (or maps), you need to schedule them on different run loop mode. Replace your current timer:

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

With this one:

NSTimer *timer = [NSTimer timerWithTimeInterval:0.5
                                           target:self
                                         selector:@selector(timerFired:)
                                         userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

For details, check this blog post: Event tracking stops NSTimer

EDIT : second block of code, the NSTimer still runs on the main thread, still on the same run loop as the scrollviews. The difference is the run loop mode. Check the blog post for a clear explanation.