当前位置:网站首页>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好的。
边栏推荐
猜你喜欢
随机推荐
IEEE在指定期刊下搜索相关论文
陕西Biotin-LC_CAS:72040-64-3_N-生物素氨基己酸供应商价格
This beta version of Typora is expired, please download and install a newer;解决方法
JSP自定义标签
VsCode打开终端的方法
《C陷阱和缺陷》void (*signal(int , void(*)(int)))(int)的深刻解读
BlockingQueue详细介绍
IO进程线程->目录IO->day3
c语言编程练习
Deep Interpretation of void (*signal(int , void(*)(int)))(int) in "C Traps and Defects"
VsCode connects to the remote server and modifies the file code
单片机第一步
ssh script space character conversion
图扑数字孪生煤矿开采系统,打造采煤“硬实力”
vscode 设置 sublime 的主题
洛谷一P1097 [NOIP2007 提高组] 统计数字
wsl2设置静态ip(固定ip)static ip
2020-09-03 Solve the very slow installation of pip install [Errno 101] Network unreachable problem
Unity Shader 标准光照模型
QT weekly skills (3)~~~~~~~~~ serial port addition

![[Common usage of markdown]](/img/4b/3cb17b1dafe095e2f45510b41186fd.png)







