Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer Reliable Alternatives

I have an application that is supposed to log certain things every 1 second and I'm currently using NSTimer, but if my application transitions screens (or almost anything else, really) it slows down the timer a little bit making for inaccurate readings.

What is a reliable alternative to use? My current code is as follows:

timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(update) userInfo:nil repeats:YES];
like image 561
Baub Avatar asked Nov 17 '11 18:11

Baub


2 Answers

NSTimer is not guaranteed to fire exactly on time, ever. But you can use an NSTimer in a much more reliable way than you are now. When you use scheduledTimerWithTimeInterval you create an NSTimer which is scheduled in the run loop for NSDefaultRunLoopMode. This mode is paused when the UI is being used, so your timers won't fire when there is user interaction. To avoid this pause use the mode NSRunLoopCommonModes. To do this you will have to schedule the timer yourself like so:

timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(update) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
like image 60
NJones Avatar answered Oct 21 '22 03:10

NJones


You could:

  • Put the NSTimer in a different thread (it may not be affected by the UI that way)
  • Decrease the interval (say 0.1 second) and, in your logging function, check if it is the "right" time to log what you want.
like image 45
Sergio Moura Avatar answered Oct 21 '22 03:10

Sergio Moura