更加精确的定时器:dispatch_source_t

时间:2022-07-21 20:33:10

在使用定时器时,我们经常使用NSTimer,但是由于NSTimer会受RunLoop影响,当RunLoop处理的任务很多时,就会导致NSTimer的精度降低,所以在一些对定时器精度要求很高的情况下,应该考虑采用GCD定时器,实现代码如下:

// 队列(队列时用来确定该定时器存在哪个队列中)
dispatch_queue_t queue = dispatch_get_main_queue();

// 创建GCD定时器
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

dispatch_time_t start
= dispatch_time(DISPATCH_TIME_NOW, 0 * NSEC_PER_SEC); // 开始时间
uint64_t interval = 2 * NSEC_PER_SEC; // 时间间隔

// 设置GCD定时器开始时间,间隔时间
dispatch_source_set_timer(_timer, start, interval, 0);

// GCD定时器处理回调方法
dispatch_source_set_event_handler(_timer, ^{
NSLog(
@"---------%@", [NSThread currentThread]);
});

// GCD定时器启动,默认是关闭的
dispatch_resume(_timer);

/**
dispatch_source_cancel(_timer); // 异步取消调度源
     
_timer = nil; // 将 dispatch_source_t 置为nil

*/