GCD timer

1.GCD提供了一个类似于NSTimer的类:dispatch_source_t

这个类的特点:

GCD的timer 不受 runloop的 mode影响,会一直执行
GCD的timer 可以做到绝对精准

//用法:

//1.创建GCD定时器
    /**
     参数1:设定soucrce的类型: DISPATCH_SOURCE_TYPE_TIMER -> 定时器类型
     参数2:描述信息,线程id
     参数3:更详细的描述信息
     参数4:队列,决定了timer在执行任务的时候在什么线程中执行
     */
    self.gcdTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_queue_create(0, 0));
    
//2.设置定时器的其他参数
    /**
     参数1:对哪一个timer进行设置
     参数2:经过多少秒后启动
     参数3:执行任务的时间间隔
     参数4:误差度 传0表示决定精准
     */
    dispatch_source_set_timer(self.gcdTimer, DISPATCH_TIME_NOW, time * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    
//3.为定时器添加需要还行的任务
    dispatch_source_set_event_handler(self.gcdTimer, action);

    
//4.启动GCD定时器
    dispatch_resume(self.gcdTimer);

为了方便使用,自己写了一个GCDTimer,支持cocopod :RFgcdTimer

你可能感兴趣的:(GCD timer)