第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);
});
网友评论