美文网首页
dispatch_source_t 定时器

dispatch_source_t 定时器

作者: 码农淏 | 来源:发表于2016-12-03 16:19 被阅读63次

NSTimer受runloop的影响, 由于runloop需要处理很多任务(scrollView 滑动等), 导致NSTimer的精度降低,在日常开发中,如果我们需要对定时器的精度要求很高的话(如启动页广告,启动页动画,需要反馈给用户的倒计时等),可以考虑dispatch_source_t去实现 。dispatch_source_t精度很高,系统自动触发,系统级别的源。下面是通过dispatch_source_t 创建 计时器的例子

 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);

相关文章

网友评论

      本文标题:dispatch_source_t 定时器

      本文链接:https://www.haomeiwen.com/subject/xjscmttx.html