美文网首页
使用NSTimer、GCD实现轮询

使用NSTimer、GCD实现轮询

作者: 阳光下的叶子呵 | 来源:发表于2021-12-11 22:43 被阅读0次

第1种、NSTimer实现轮询

@property (nonatomic, strong) NSTimer *timer;

#pragma mark - 轮询 (判断是否 取消比赛)
- (void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark - Public
- (void)start {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
}

- (void)stop {
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark - Private
- (void)doSomething {
    // Do something
}

第2种、GCD方法轮询

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);
});

相关文章

网友评论

      本文标题:使用NSTimer、GCD实现轮询

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