dispatch source timer

12,917 阅读1分钟

使用

dispatch_source_create
dispatch_source_set_timer
dispatch_source_set_event_handler
dispatch_resume
dispatch_suspend
dispatch_cancel

备注

timer 销毁使用 dispatch_cancel,须在dispatch_resume状态下执行 cancel

关键实现

- (void)createTimer {

    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue);
    dispatch_source_set_timer(self.timer, dispatch_walltime(**NULL**, 0), 1.0 * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC);

    dispatch_source_set_event_handler(self.timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            // task
        });

    });

}

- (void)startTimer {

    dispatch_resume(self.timer);

    self.stopped = NO;

    NSLog(@"timer started ... ");

}
- (void)stopTimer {

    dispatch_suspend(self.timer);

    self.stopped = YES;

    NSLog(@"timer suspended ... ");

}
- (void)destroyTimer {
    if (self.stopped) {

        [self startTimer];

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            dispatch_cancel(self.timer);

            self.stopped = YES;

            self.timer = nil;

            NSLog(@"timer destroyed ... ");

        });

    } else {

        dispatch_cancel(self.timer);

        self.stopped = YES;

        self.timer = nil;

        NSLog(@"timer destroyed ... ");

    }
}

完整项目

github.com/githubwbp19…