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

     

  • 相关阅读:
    [Java]lambda表达式
    [设计模式]访问者模式
    【Java】基本数据类型
    【JavaWeb】防止表单的重复提交
    [Java]异常在项目中的使用
    Java容器-个人整理1
    【MyBatis-Spring】Mybatis和并入Spring框架
    python 正则表达式模块——re 知识点小结
    关于使用python批量操作网络设备(交换机,路由器)的知识点小结
    GitHub 基础常用命令用法
  • 原文地址:https://www.cnblogs.com/HJiang/p/7497529.html
Copyright © 2011-2022 走看看