I’m trying to add multiple timers to a thread, not the main thread.Here is code:
- (IBAction)addTimer:(id)sender
{
if (!_timerQueue) {
_timerQueue = dispatch_queue_create("timer_queue", NULL);
}
dispatch_async(_timerQueue, ^{
NSTimer *tempTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:tempTimer forMode:NSRunLoopCommonModes];
[[NSRunLoop currentRunLoop] run];
});
}
The method above is triggered by a button action. But the code in the dispatch block runs only once not matter how many times i click the button. So only one Timer in that thread. I wonder why?
The reason why you only see one timer at a time is in the last line of your dispatch block:
-[NSRunLoop run]is a blocking call that returns when the last input source of the run loop finishes and no timers are scheduled anymore.In addition, GCD-queues are strictly FIFO and you are creating a serial queue.
Thus, the result of you tapping that button several times is a queue that gets fuller and fuller without the first block ever finishing:
Since the timer is repeating, there always is something scheduled on the run loop and thus
runnever returns, barring all subsequent blocks from ever being invoked.