OC原理之GCD定时器

由于NSTimer依赖于RunLoop,如果RunLoop的任务过于繁重,导致RunLoop执行一圈的时间不确定,可能回到NSTimer的

不准时,如果你需要高精度的定时器,那么GCD的定时器会符合你的需求,使用代码如下:

// 创建定时器
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

// 设置时间(start: 代表多久之后开始执行, interval: 执行时间间隔)
dispatch_source_set_timer(timer,
                              dispatch_time(DISPATCH_TIME_NOW, start * NSEC_PER_SEC),
                              interval * NSEC_PER_SEC, 0);

// 设置回调
dispatch_source_set_event_handler(timer, ^{
        task();
        
});

// 启动定时器
dispatch_resume(timer);
原文地址:https://www.cnblogs.com/muzichenyu/p/14455182.html