GCD定时器优点:① GCD定时器不受RunLoop约束② 比NSTimer更加准时。
GCD定时器用法
敲 dispatch_source_选择第一个提示的代码段,注意不是dispatch_time,而是dispatch_source_.
敲完dispatch_source并选择第一个,就会有下面代码段的提示:
这里参数比较多,我们先来看下各个参数的含义,然后再学习怎么使用。
//1.创建GCD中的定时器
/**
参数1:source的类型DISPATCH_SOURCE_TYPE_TIMER,表示定时器
参数2:描述信息
参数3:更详细的描述信息
参数4:队列,决定GCD定时器中的任务在那线程中执行
*/
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//2.设置定时器(起始时间 | 间隔时间 | 精准度)
/**
参数1:定时器对象timer
参数2:起始时间,DISPATCH_TIME_NOW,从现在开始计时
参数3:时间间隔1.0 ,时间间隔为纳秒
参数4:精准度,绝对精准为0
*/
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
//3.设置定时器要执行的任务
dispatch_source_set_event_handler(timer, ^{
NSLog(@"GCD----%@",[NSThread currentThread]);
});
//4.启动执行定时器
dispatch_resume(timer);
注意:此时我们启动执行,定时器是不会工作的,虽然我们通过 dispatch_resume(timer) 启动了定时器,但是dispatch_source_t timer是个局部对象,创建完就释放了,所以我们需要个全局的timer属性来进行强引用。
所以修改后可执行的代码如下所示:
@interface ViewController ()
/// gcd timer
@property (nonatomic, strong) dispatch_source_t timer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"----点击了------");
//1.创建GCD中的定时器
/**
参数1:source的类型DISPATCH_SOURCE_TYPE_TIMER,表示定时器
参数2:描述信息
参数3:更详细的描述信息
参数4:队列,决定GCD定时器中的任务在那线程中执行
*/
// dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
// dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_queue_t queue = dispatch_queue_create("timerQueue", DISPATCH_QUEUE_SERIAL);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//2.设置定时器(起始时间 | 间隔时间 | 精准度)
/**
参数1:定时器对象timer
参数2:起始时间,DISPATCH_TIME_NOW,从现在开始计时
参数3:时间间隔1.0 ,时间间隔为纳秒
参数4:精准度,绝对精准为0
*/
uint64_t start = 2.0; //2后开始执行
uint64_t interval = 1.0;//每隔1s执行
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, start * NSEC_PER_SEC, interval * NSEC_PER_SEC);
//3.设置定时器要执行的任务
dispatch_source_set_event_handler(timer, ^{
NSLog(@"GCD----%@",[NSThread currentThread]);
});
//4.启动执行定时器
dispatch_resume(timer);
self.timer = timer;
}
GCD定时器是和系统内核直接挂钩的和runloop没有任何关系,所以GCD定时器比NSTimer要准时,而且GCD创建的都想,不需要手动销毁。
Tips:
如果项目中多处都需要用到定时器,虽然GCD定时器好用,但是GCD定时器的创建代码较为冗长,所以为了项目中方便使用,稍加封装,写了个GCDTimer定时器的封装,供大家参考学习。
用法示例:
@interface ViewController ()
/// 定时器名字
@property (nonatomic, copy) NSString * timerName;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"begin");
//创建定时器
self.timerName = [GCDTimer executeTask:^{
NSLog(@">>>>> GCDTimer %@",[NSThread currentThread]);
} start:1.0 interval:1.0 repeat:YES async:NO];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"----点击取消------");
[GCDTimer cancleTask:self.timerName];
}