更加精确的定时器:dispatch_source_t

Posted ~~Sharp~~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了更加精确的定时器:dispatch_source_t相关的知识,希望对你有一定的参考价值。

在使用定时器时,我们经常使用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_t
        dispatch_source_cancel(_timer);
     */

 

以上是关于更加精确的定时器:dispatch_source_t的主要内容,如果未能解决你的问题,请参考以下文章

STM32F4的PWM脉冲数量精确输出

iOS NSTimer定时器

iOS NSTimer定时器

iOS NSTimer定时器

Linux_arm驱动之按键模拟脉冲实现定时器的精确计时

iOS中的定时器