0

Now I am creating a metronome program. I use a NSTimer to bring the metronome into play. Of course The Timer works repeatedly. But I find out in two situation that the timer works not accruately.

  1. When just start the NSTimer, the first two beat sometimes goes too closely. After then, the beat goes evenly.

  2. When the app goes backgound I make the Timer work continuely by:

    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];

    but sometimes the unevenly beat also happens at the time when entering or coming back from the background status.

So I want to know how to keep the Timer always work evenly, no matter which situation it is in. Thks!

Community
  • 1
  • 1
itenyh
  • 1,921
  • 2
  • 23
  • 38

1 Answers1

1

When setting up a timer firing at a certain time, the system implicitly sets an allowed "leeway" which is a short delay within the timer may actually fire.

This is due to "Timer Coalescing" - a system feature - which groups events happening roughly at the same time together and fire them at the exact same time. The reason is to reduce CPU cycles and extend the idle time of the CPU to save power.

If the timer interval is small (milli seconds to seconds) this "leeway" is in the range of 10% of the timer interval.

You can explicitly retrieve and set the current maximum allowed leeway value with the methods

-tolerance

-setTolerance:

See also:

NSTimer

Timing Accuracy

CouchDeveloper
  • 18,174
  • 3
  • 45
  • 67