GCD定时器

作者: 流行的武 | 来源:发表于2016-04-14 16:23 被阅读139次

使用GCD设置定时器比NSTimer要准确一些,而且不会受RunLoop不同模式的的影响

设置全局变量timer,如果不设置成全局的话会被销毁掉

//timer是一个OC对象
@property (nonatomic ,strong)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);
    dispatch_time_t interval = 2.0 * NSEC_PER_SEC;
    dispatch_source_set_timer(self.timer, start, interval, 0);
    
    //设置回调
    dispatch_source_set_event_handler(self.timer, ^{
        NSLog(@"----%@",[NSThread currentThread]);
    });
    
    //启动定时器
    dispatch_resume(self.timer);

暂停定时器

dispatch_cancel(self.timer);

相关文章

网友评论

    本文标题:GCD定时器

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