美文网首页iOS机制
GCD实现定时器功能

GCD实现定时器功能

作者: coderJerry01 | 来源:发表于2022-03-08 19:32 被阅读0次
 static dispatch_source_t _timer;
 _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); 
 dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 2 * NSEC_PER_SEC, 0); //每秒执行
dispatch_source_set_event_handler(_timer, ^{
    dispatch_async(dispatch_get_main_queue(), ^{
        //需要轮询的内容
    });
});
// 开启定时器
dispatch_resume(_timer);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    // 轮询超时
    dispatch_cancel(_timer);
});

相关文章

网友评论

    本文标题:GCD实现定时器功能

    本文链接:https://www.haomeiwen.com/subject/noaarrtx.html