Reputation: 1882
I'm somewhat new to objective-c. So, if my question or code looks odd, that would explain why. I have a NSTimer which is fired every 0.033 seconds.
timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(timerCallback) userInfo:nil repeats:YES];
The selector function looks like this:
BOOL running = false;
- (void) timerCallback
{
if (running) {
return;
}
running = true;
//Do some stuff
running = false;
}
Thing is, the function timerCallback has to be fired at these intervals no matter what to maintain the sync. (skipping going into detail)
But... as it turns out, the timerCallback function causes the NSTimer to stop and wait for it to complete before resuming?
What options do I have to maintain the interval? Can the timerCallback function be executed in a separate thread? Are there better options than NSTimer? Perhaps a separate thread to begin with?
Upvotes: 1
Views: 816
Reputation: 149
I would suggest using something like this, to prevent blocking.
BOOL running = false;
- (void) timerCallback
{
if (running) {
return;
}
[(NSOperationQueue*)_myOperationQueue addOperationWithBlock:^{
running = true;
//do Some Stuff
running = false
}];
}
Upvotes: 2
Reputation: 41642
The timer will attempt to maintaing the desired firing interval averaged over time - since it cannot provide exact timing due to the design of NSTimer and NSRunLoop. If your code in he timer is taking over 0.033 seconds, I'm not sure if the timer will skip one call or not - it might
Try this experiment - set the timer, then comment out all your work, and log the time. It should be very close to the desired time. That said, at 30 calls a second, if you are touching the UI at all this is close to the maximum performance you could expect to get.
One strategy to minimize the amount of variation is to put all the code you are doing inside a block, and dispatch it either to the main queue, or better yet, dispatch it to a concurrent thread. That way you will return from the call in a very short period of time.
If this does not do if for you, look at CADisplayLink. You can get very precise callback using this capability, as it runs at a very high priority. However, you cannot do anything substantial in the callback as you only get a sliver of time. You can however dispatch blocks to a queue for processing on the main queue (main thread).
Upvotes: 0