objective-ccocoanstimernsrunloopnsblockoperation

How do I create a NSTimer on a background thread?


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.


Solution

  • The timer would need to be installed into a run loop operating on an already-running background thread. That thread would have to continue to run the run loop to have the timer actually fire. And for that background thread to continue being able to fire other timer events, it would need to spawn a new thread to actually handle events anyway (assuming, of course, that the processing you're doing takes a significant amount of time).

    For whatever it's worth, I think handling timer events by spawning a new thread using Grand Central Dispatch or NSBlockOperation is a perfectly reasonable use of your main thread.