NSTimer会是准时触发事件吗

来源:互联网 发布:java删除文件 编辑:程序博客网 时间:2024/04/30 03:52

NSTimer会是准时触发事件吗?
  答案是否定的,而且有时候你会发现实际的触发时间跟你想象的差距还比较大。
        NSTimer不是一个实时系统,因此不管是一次性的还是周期性的timer的实际触发事件的时间可能都会跟我们预想的会有出入。差距的大小跟当前我们程序的执行情况有关系,比如可能程序是多线程的,而你的timer只是添加在某一个线程的runloop的某一种指定的runloopmode中,由于多线程通常都是分时执行的,而且每次执行的mode也可能随着实际情况发生变化。
  假设你添加了一个timer指定2秒后触发某一个事件,但是,恰好那个时候当前线程在执行一个连续运算(例如大数据块的处理等),这个时候timer就会延迟到该连续运算执行完以后才会执行。重复性的timer遇到这种情况,如果延迟超过了一个周期,则会和后面的触发进行合并,即在一个周期内只会触发一次。但是不管该timer的触发时间延迟的有多离谱,他后面的timer的触发时间总是倍数于第一次添加timer的间隙。
  原文如下“A repeating timer reschedules itself based on the scheduled firing time, not the actual firing time. For example, if a timer is scheduled to fire at a particular time and every 5 seconds after that, the scheduled firing time will always fall on the original 5 second time intervals, even if the actual firing time gets delayed. If the firing time is delayed so far that it passes one or more of the scheduled firing times, the timer is fired only once for that time period; the timer is then rescheduled, after firing, for the next scheduled firing time in the future.”
  下面请看一个简单的例子:

Simulate Thread Busy- (void)applicationDidBecomeActive:(UIApplication *)application{    SvTestObject *testObject2 = [[SvTestObject alloc] init];    [NSTimer scheduledTimerWithTimeInterval:1 target:testObject2 selector:@selector(timerAction:) userInfo:nil repeats:YES];    [testObject2 release];        NSLog(@"Simulate busy");    [self performSelector:@selector(simulateBusy) withObject:nil afterDelay:3];}// 模拟当前线程正好繁忙的情况- (void)simulateBusy{    NSLog(@"start simulate busy!");    NSUInteger caculateCount = 0x0FFFFFFF;    CGFloat uselessValue = 0;    for (NSUInteger i = 0; i < caculateCount; ++i) {        uselessValue = i / 0.3333;    }    NSLog(@"finish simulate busy!");}

        例子中首先开启了一个timer,这个timer每隔1秒调用一次target的timerAction方法,紧接着我们在3秒后调用了一个模拟线程繁忙的方法(其实就是一个大的循环)。运行程序后输出结果如下:


        观察结果我们可以发现,当线程空闲的时候timer的消息触发还是比较准确的,但是在36分12秒开始线程一直忙着做大量运算,直到36分14秒该运算才结束,这个时候timer才触发消息,这个线程繁忙的过程超过了一个周期,但是timer并没有连着触发两次消息,而只是触发了一次。等线程忙完以后后面的消息触发的时间仍然都是整数倍与开始我们指定的时间,这也从侧面证明,timer并不会因为触发延迟而导致后面的触发时间发生延迟。
  综上: timer不是一种实时的机制,会存在延迟,而且延迟的程度跟当前线程的执行情况有关。

转载处:NSTimer你真的会用了吗

1 0
原创粉丝点击