自己封装的GCD定时器方法

2016-08-31  本文已影响33人  zcaaron
这是一个单例

- (void)scheduledDispatchTimerWithName:(NSString *)timeName timeInterval:(double)interval queue:(dispatch_queue_t)queue repeats:(BOOL)repeats action:(dispatch_block_t)action{

      if(nil == timerName) return;
      if(nil == queue){
         queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
         dispatch_source_t timer = [self.timerContainer objectForKey:timerName];
      }
     if(!timer){
         timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,queue);
         dispatch_resume(timer);
        [self.timerContainer setObject:timer forKey:timeName];
     }
     dispatch_source_set_timer(timer,dispatch_time(DISPATCH_TIME_NOW,interval*NSEC_PER_SEC),interval*NSEC_PER_SEC,0.1*NSEC_PER_SEC);

     __weak typeof(self) weakSelf = self;
    dispatch_source_set_event_handler(timer,^{
       action();
       if(!repeats){
       [weakSelf cancelTimerWithName:timerName];
       }
    });
}

- (void)cancelTimerWithName:(NSString*)timerName{

        dispatch_source_t timer = [self.timerContainer objectForKey:timerName];

        if (!timer) return;

        [self.timerContainer removeObjectForKey:timerName];

        dispatch_source_cancel(timer);
}
上一篇下一篇

猜你喜欢

热点阅读