zoukankan      html  css  js  c++  java
  • GCD dispatch_source基本使用,创建GCD定时器与NSTimer的区别

    可以使用GCD创建定时器

    创建定时器:

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        
        self.timer = timer;
        
        // 定时任务调度设置,4秒后启动,每个5秒运行
        dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW , 4);
        dispatch_source_set_timer(self.timer, time, 5 * NSEC_PER_SEC, 3 * NSEC_PER_SEC);
        
        dispatch_source_set_event_handler(self.timer, ^{
            // 定时任务
            NSLog(@"%s",__func__);
        });
        
        dispatch_source_set_cancel_handler(self.timer, ^{
            // 定时取消回调
            NSLog(@"source did cancel...");
        });
        
        // 启动定时器
        dispatch_resume(timer);

    注意创建gcd定时器timer后,需要保存timer,需要有个引用引用timer,要不然timer会销毁

    @property (nonatomic, strong) dispatch_source_t timer;
    

    取消定时器

        dispatch_source_cancel(self.timer);
        self.timer = nil;
    

      

    总结

    GCD定时器

             1.时间调度很准确,时间是以纳秒为单位,NSTimer更加精确

             2.GCD是不受runloop的影响, 比如:拖动scrollView,不会影响GCD定时器的运行

    NSTimer定时器

             1.时间调度可能会有误差,时间是以秒为单位,GCD timer精确

             2.runloop的影响比如:拖动scrollView,会影响定时器的运行

     

  • 相关阅读:
    字典或者数组与JSON串之间的转换
    银联支付 支付代码
    iOS 一个新方法:- (void)makeObjectsPerformSelector:(SEL)aSelector;
    iOS 直接使用16进制颜色
    iOS 添加view的分类(更加方便的设置view的位置)
    iOS 中UITableView的深理解
    Swift 中调试状态下打印日志
    手把手教React Native实战开发视频教程【更新到40集啦。。。】
    React Native 开发
    React-Native学习指南
  • 原文地址:https://www.cnblogs.com/HJiang/p/7497529.html
Copyright © 2011-2022 走看看