Skip to content

Instantly share code, notes, and snippets.

@zhangkn
Last active May 4, 2018 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangkn/1a6e6d4df19d8cb47487f20f0bd76ec4 to your computer and use it in GitHub Desktop.
Save zhangkn/1a6e6d4df19d8cb47487f20f0bd76ec4 to your computer and use it in GitHub Desktop.
创建GCD定时器
// 创建GCD定时器
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//创建dispatch_source_t
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//设置dispatch_source_t的属性
//参数二:使用 `dispatch_time` 或者 `DISPATCH_TIME_NOW` 时,系统会使用默认时钟来进行计时。然而当系统休眠的时候,默认时钟是不走的
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0); //每秒执行,使用 `dispatch_walltime ` 可以让计时器按照真实时间间隔进行计时.
// 事件回调
dispatch_source_set_event_handler(_timer, ^{//在子线程中执行任务
dispatch_async(dispatch_get_main_queue(), ^{//通过dispatch_get_main_queue回到主线程
// 在主线程中实现需要的功能
}
}
});
// 开启定时器
dispatch_resume(_timer);
// 挂起定时器(dispatch_suspend 之后的 Timer,是不能被释放的!会引起崩溃)
dispatch_suspend(_timer);
// 关闭定时器
dispatch_source_cancel(_timer);//若我们想无限循环可将dispatch_source_cancel、dispatch_suspend写在一句永不执行的`if`判断语句中
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment