您的位置:首页 > 移动开发 > IOS开发

GCD实现定时器

2015-11-10 00:00 197 查看
摘要: GCD实现定时器

GCD学习(二)

(1)dispatch source创建定时器

//dispatch source定时器
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_queue_t mainq = dispatch_get_main_queue();//主线程

if (source) {

dispatch_source_set_timer(source, dispatch_walltime(DISPATCH_TIME_NOW, 0), 2 * NSEC_PER_SEC, 0);

dispatch_source_set_event_handler(source, ^{

dispatch_async(mainq, ^{

[self testTimerOper];
});

});
}

dispatch_resume(source);

//用户执行操作
-(void)testTimerOper {

NSLog(@"测试timer执行");
}

上述例子每2秒会执行一次testTimerOper函数;可以使用dispatch_source_cancel(source)关闭定时器。

注意:dispatch_source_t source 须定义为全局变量,否则会被释放导致运行不成功。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  IOS 多线程 GCD 定时器