iOS的定时器用法
2016-03-11 00:00
519 查看
摘要: 介绍iOS中定时器的三种用法
定时器在项目中还是经常用到的,很多情况下为了省事我们都是在主线程中直接用,但这样经常会造成阻塞,影响定时器的准确性,对时间精度要求比较高的地方还会给人很不好的体验,比如卡顿等等,所以,定时器的使用最好放在子线程中,下面就记录几种定时器的用法:
1、NSThread
2、GCD
首先定义timer:
这里有一点疑惑:timer若作为成员变量(定义放在@interface里面)定时器可以正常使用,但是在方法里面再去定义的定义的话定时器就完全不起作用了,还请知道的原因的小伙伴多多指教:
GCD的形式有很多种,下面再列举两种:
定时器在项目中还是经常用到的,很多情况下为了省事我们都是在主线程中直接用,但这样经常会造成阻塞,影响定时器的准确性,对时间精度要求比较高的地方还会给人很不好的体验,比如卡顿等等,所以,定时器的使用最好放在子线程中,下面就记录几种定时器的用法:
1、NSThread
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil]; [thread start]; - (void)newThread{ @autoreleasepool{ [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(requestMessages) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] run]; } }
2、GCD
首先定义timer:
这里有一点疑惑:timer若作为成员变量(定义放在@interface里面)定时器可以正常使用,但是在方法里面再去定义的定义的话定时器就完全不起作用了,还请知道的原因的小伙伴多多指教:
NSTimeInterval period = 60.0; //设置时间间隔 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); _timers = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(_timers, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); dispatch_source_set_event_handler(_timers, ^{ //在这里执行事件 kDLOG(@"定时时间到"); [self requestMessages]; }); dispatch_resume(_timers);
GCD的形式有很多种,下面再列举两种:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); _timers = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)); uint64_t interval = (uint64_t)(10.0 * NSEC_PER_SEC); dispatch_source_set_timer(_timers, start, interval, 0); // 设置回调 dispatch_source_set_event_handler(_timers, ^{ kDLOG(@"多线程定时时间到"); [self requestMessages]; }); // 启动定时器 dispatch_resume(_timers);
uint64_t interval = 3 * NSEC_PER_SEC; dispatch_queue_t queue = dispatch_queue_create("my queue", 0); _timers = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(_timers, dispatch_time(DISPATCH_TIME_NOW, 0), interval, 0); dispatch_source_set_event_handler(_timers, ^(){ kDLOG(@"定时时间到"); }); dispatch_resume(_timers);
相关文章推荐
- Mootools 1.2教程 定时器和哈希简介
- C#定时器和随机数
- C#中timer定时器用法实例
- JS中自定义定时器让它在某一时刻执行
- 理解javascript定时器中的setTimeout与setInterval
- JavaScript定时器详解及实例
- 基于jQuery实现的扇形定时器附源码下载
- 跟我学习javascript的定时器
- Qt定时器和随机数详解
- asp.net中Timer无刷新定时器的实现方法
- 解析Java中的定时器及使用定时器制作弹弹球游戏的示例
- libevent库的使用--定时器的使用实例
- MySQL定时器EVENT学习笔记
- js函数定时器实现定时读取系统实时连接数
- linux使用select实现精确定时器详解
- Cocos2d-x Schedule定时器的使用实例
- VC定时器的用法实例详解
- javascript设计简单的秒表计时器
- c#定时器和global实现自动job示例
- JavaScript学习笔记之定时器