GCD计时器的相关操作

集团项目需要在网络请求的时候添加一个计时器,NSTimer有什么缺点我就不说了,今天说下GCD做计时器的一些心得。
创建计时器

@property (nonatomic, strong) dispatch_source_t timer;//创建一个全局的timer

self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);//开始时间:从现在开始1秒后开始
    dispatch_source_set_timer(self.timer, start, (int64_t)(1.0 * NSEC_PER_SEC), 0);
    
    dispatch_source_set_event_handler(self.timer, ^{
//        计时器计时中需要执行的方法
        [self timerMethod1];
    });

//开启计时器
dispatch_resume(self.timer);
//关闭计时器
dispatch_cancel(self.timer);

使用这个方法关闭计时器,timer会置nil,如果循环使用计时器,再次执行开启计时器的方法,就会出现闪退情况,可以使用下面的方法暂停计时器

dispatch_suspend(self.timer);

这样下次启动计时器就可以正常使用了。

你可能感兴趣的:(GCD计时器的相关操作)