当前位置:网站首页>GCD的定时器
GCD的定时器
2022-07-30 05:48:00 【大黄_黄】
首先需要说明一点:GCD的定时器和NSTimer是不一样的,NSTimer受RunLoop影响,但是GCD的定时器不受影响,因为RunLoop也是基于GCD的(源代码可知)。
接下来看CGD定时器的具体实现(分为以下几步):
- 创建定时器
// 获得队列
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
// 创建定时器
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
注意:这里的定时器(dispatch_source_t类型)其实是个OC对象,所以必须强引用。
- 设置定时器的开始时间,间隔时间
// 设置定时器的各种属性(几时开启任务,多长时间执行一次任务)
// GCD的时间参数是纳秒(1秒 == 10的9次方纳秒), NSEC_PER_SEC就代表10的9次方纳秒
dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)); // 比当前时间晚3秒
uint64_t interval = 1.0 * NSEC_PER_SEC; // 间隔时间
dispatch_source_set_timer(self.timer, start, interval, 0);
- 设置回调
// 设置回调
dispatch_source_set_event_handler(self.timer, ^{
NSLog(@"-----TorSinLee-----");
});
- 启动定时器
// 启动定时器
dispatch_resume(self.timer);
- 关闭定时器
// 取消定时器
dispatch_cancel(self.timer);
可以看出,GCD的定时器实现要比NSTimer复杂得多了,但是GCD的定时器的时间准确性是要比NSTimer好的。
边栏推荐
- Insert map data efficiently
- Real-time waveform display of CAN communication data based on QT (serial eight) ==== "Sub function or new class calls ui control"
- Vim查找字符
- vscode set sublime theme
- Unity Gizmos扩展:线框圆
- 基于STM32F103的消防系统之MQ-4气体传感器
- (*(void (*)())0)()的解读
- The IEEE under the specified journal search related papers
- 题解——汉明距离
- 掌握JESD204B(三)–AD6676的调试
猜你喜欢
[Common usage of markdown]
This beta version of Typora is expired, please download and install a newer;解决方法
ES6 syntax notes (ES6~ES11)
This beta version of Typora is expired, please download and install a newer; workaround
【JVM】线上应用故障排查
陕西Biotin-LC_CAS:72040-64-3_N-生物素氨基己酸供应商价格
THREEJS导入外部OBJ+MTL后内存优化
D-Desthiobiotin|D-脱硫生物素|CAS:533-48-2用于蛋白质和细胞的标记
SSH-RSA密钥
Word使用中常用的快捷键
随机推荐
The IEEE under the specified journal search related papers
Desthiobiotin-PEG4-Acid|脱硫生物素-PEG4-酸| 供应商和制造商
Insert map data efficiently
独立按键控制led
比尔·盖茨买百万亩农地成美“头号地主”,图扑数字孪生农场
无法完成包的安装npm ERR! Refusing to install package with name “moment“ under a package also called “moment“
基于STM32F103的消防系统之驱动电机风扇
STM32F103连接L9110S电机驱动控制小水泵
基于精灵(Sprite)管道烟雾流动效果
洛谷一P1097 [NOIP2007 提高组] 统计数字
Biotin-SS-NHS ester|生物素-二硫键-活性酯|CAS:122266-55-1具有良好的水溶性
wsl2设置静态ip(固定ip)static ip
rsync使用方法之坑
ThreeJS导入外部obj和mtl
迷宫问题----经典回溯法解决
Biotin-PEG4-DADPS-Picolyl-azide(CAS:2599839-59-3)生物素试剂
The most complete difference between sizeof and strlen, as well as pointer and array operation analysis
删除当前路径下含某个关键字的所有文件
如何将modelsim仿真数据存成文件
PC DBCO-PEG3-Biotin|PC-生物素-PEG3-DBCO可用于使用无铜点击化学