NSTimer不准确问题

来源:互联网 发布:网络电影发展 编辑:程序博客网 时间:2024/04/29 09:52

参考

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/index.html


A timer is not a real-time mechanism; it fires only when one of the run loop modes to which the timer has been added is running and able to check if the 

timer's firing time has passed. Because of the various input sources a typical run loop manages, the effective resolution of the timer interval for a timer

is limited to on the order of 50-100 milliseconds. If a timer's firing timer occurs during a long callout or while the run loop is in a mode that is not monitoring

the timer , the timer does not fire until the next time the run loop checks the timer. Therefore, the actual time at which the timer fires potentially can be a 

significant period of time after the scheduled firing time.


NSTimer 不是一个基于真实时间的机制。NSTimer被激发需要满足三个条件,

第一,NSTimer被添加到特定mode的runloop中;

第二该mode型的runloop正在运行;

第三,到达激发时间。因为一个run loop需要管理大量的输入源,为了提NSTimer的效率,时间间隔限制为50-100毫秒比较合理。如果一个NSTimer的激发时间

出现在一个耗时的方法中,或者当前run loop的mode没有监测该NSTimer,那么定时器就不会被激发,直到下一次run loop检测到该NSTimer时才会激发。

因此,NSTimer的实际激发时间很有可能会比规划时间延后一段时间。

参考 https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-131281

Although it generates time-based notifications, a timer is not a real-time mechanism. Like input sources, timers are associated with specific modes of your run loop. If a timer is not in the mode currently being monitored by the run loop, it does not fire until you run the run loop in one of the timer’s supported modes. Similarly, if a timer fires when the run loop is in the middle of executing a handler routine, the timer waits until the next time through the run loop to invoke its handler routine. If the run loop is not running at all, the timer never fires.

即使NSTimer会基于时间发出通知,但是NSTimer不是一个基于真实时间的机制。和输入源一样,timer和指定mode型的run loop紧密联系。如果没有被当前mode型的run loop监测,timer就不会激发,直到timer指定的mode型的run loop运行时才会被激发。类似的,当timer的激发时间到达,而这时run loop又恰好在执行一个handler,那么timer不会被激发,而是等到下一次的激发时间点通过run loop来唤醒timer的handler。如果run loop不再运行,那么timer就永远不再被激发。

0 0
原创粉丝点击