-(void)viewDidLoad{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[NSTimer scheduledTimerWithTimeInterval:0.10
target:self
selector:@selector(action_Timer)
userInfo:nil
repeats:YES];
}
);
}
-(void)action_Timer{
LOG("Timer called");
}
action_Timer
is not being called. I dont know why. Do you have any idea?
You have to add the timer to the main run loop for the timer to fire, but first, you should hold reference to to the timer in a private ivar or a property:
I find easier to get off the main queue in the called method. At somepoint, maybe in
viewDidUnlod
or indealloc
, you will have call[self.myTimer invalidate]; self.myTimer = nil;
.You're calling
+[NSTimer scheduledTimerWithTimeInterval:...]
from a GCD worker thread. GCD worker threads don't run a run loop. That's why your first try didn't work.When you tried
[[NSRunLoop mainRunLoop] addTimer:myTimer forMode:NSDefaultRunLoopMode]
, you were sending a message to the main run loop from a GCD worker thread. The problem there isNSRunLoop
is not thread-safe. (This is documented in the NSRunLoop Class Reference.)Instead, you need to dispatch back to the main queue so that when you send the
addTimer:...
message to the main run loop, it's done on the main thread.Realistically, there's no reason to create the timer on the background queue if you're going to schedule it in the main run loop. You can just dispatch back to the main queue to create and schedule it:
Note that both of my solutions add the timer to the main run loop, so the timer's action will run on the main thread. If you want the timer's action to run on a background queue, you should dispatch to it from the action: