美文网首页
GCD定时器

GCD定时器

作者: 博尔茨杰 | 来源:发表于2018-08-10 14:02 被阅读12次

GCD定时器有几个注意的点
1.定时器在运行状态才能取消,如果挂起状态取消就会崩溃。
2.在GCD中没有判断是否正在运行的属性,只能我们自己代码进行判断。

//GCD定时器, 创建GCD定时器
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t gcdtimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(gcdtimer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0); //每秒执行
    
//事件回调
dispatch_source_set_event_handler(gcdtimer, ^{

  dispatch_async(dispatch_get_main_queue(), ^{
  //在主线程中实现需要的功能     
  
  });

});

// 运行定时器
dispatch_resume(gcdtimer);
//挂起定时器
dispatch_suspend(gcdtimer);
// 关闭定时器
dispatch_source_cancel(gcdtimer);

相关文章

网友评论

      本文标题:GCD定时器

      本文链接:https://www.haomeiwen.com/subject/snvkbftx.html