GCD定时器
#####1.1.GCD定时器基本应用
-(void) baseGCD{
//创建一个GCD定时器
//<#dispatch_source_type_t type#> DISPATCH_SOURCE_TYPE_TIMER
self.timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0 ));
//设置定时器什么时候起动,间隔是多少
dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 2.0*NSEC_PER_SEC, 0);
//设置定时器要做的事情
dispatch_source_set_event_handler(self.timer, ^{
NSLog(@"start --v%@",[NSThread currentThread]);
});
//定时器默认是没有启动的,所以要托运启动
dispatch_resume(self.timer);
}
#####2.1.加强版GCD
int count=0;
-(void) GCD{
//GCD不受runLoop模式的影响
dispatch_queue_t queue=dispatch_get_global_queue(0, 0);
//创建一个GCD定时器
//DISPATCH_SOURCE_TYPE_TIMER
self.timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//设置定时器什么时候起动,间隔是多少
//when:何时开始
dispatch_time_t start=dispatch_time(DISPATCH_TIME_NOW, 3.0*NSEC_PER_SEC);
//间隔
uint64_t interval=2.0*NSEC_PER_SEC;
dispatch_source_set_timer(self.timer, start, interval, 0);
//设置定时器要做的事情
dispatch_source_set_event_handler(self.timer, ^{
NSLog(@"start --v%@",[NSThread currentThread]);
//执行五次后自动释放gcd
count++;
if (count>4) {
dispatch_cancel(self.timer);
self.timer=nil;
}
});
//定时器默认是没有启动的,所以要托运启动
dispatch_resume(self.timer);
}
来源:oschina
链接:https://my.oschina.net/u/2689738/blog/725515