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,会影响定时器的运行

     

  • 相关阅读:
    18.centos7基础学习与积累-004-分区理论
    绑定省份到select控件
    c#编写1-2+3-4……m
    在写按时间段查询的sql语句的时候 一般我们会这么写查询条件:
    二进制移位运算
    构造datatable临时数据
    svn代表四种检出深度
    关于TTS SpeechVoiceSpeakFlags几个值的中文意思?
    user32.dll中的所有函数
    xaml 微软帮助 url
  • 原文地址:https://www.cnblogs.com/HJiang/p/7497529.html
Copyright © 2011-2022 走看看