比NStimer准确的定时器(GCD)

来源:互联网 发布:淘宝账号登录首页 编辑:程序博客网 时间:2024/05/10 13:53
NSTimer受runloop的影响,由于runloop需要处理很多任务,导致NSTimer的精度降低,在日常开发中,如果我们需要对定时器的精度要求很高的话,可以考虑dispatch_source_t去实现 。dispatch_source_t精度很高,系统自动触发,系统级别的源。下面是通过dispatch_source_t 创建 计时器的例子
dispatch_source_t  _timer;
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);    //开始时间    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, 3.0 * NSEC_PER_SEC);    //间隔时间    uint64_t interval = 2.0 * NSEC_PER_SEC;    dispatch_source_set_timer(self.timer, start, interval, 0);    //设置回调    dispatch_source_set_event_handler(self.timer, ^{        NSLog(@"----self.timer---");    });    //启动timer    dispatch_resume(self.timer);