GCD Timer

作者: osnail | 来源:发表于2019-05-30 10:09 被阅读0次

    倒计时 定时器 timer

    -(void)gcdTimeStartTime:(NSInteger)startTime withBlock:(void(^)(NSInteger time))currentTime {
        dispatch_queue_t queue = dispatch_get_main_queue();
        __block dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        __block NSInteger count  = startTime;
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(timer, ^{
            count --;
            currentTime(count);
            if (count == 0) {
               dispatch_source_cancel(timer);
            }
        });
        dispatch_resume(timer);
        
    }
    

    循环执行定时器

    @property (nonatomic ,strong) dispatch_source_t timer;//  注意:此处应该使用强引用 strong
    -------------------------------------------------------------------------------
    /**
     gcd 事件函数
     @param sleepTime 每多少秒发生一次
     @param currentTime 当前是第几次
     */
    -(void)gcdEventTime:(NSInteger)sleepTime withBlock:(void(^)(NSInteger time))currentTime {
        
        if (self.timer) {
            return;
        }
        
        dispatch_queue_t queue = dispatch_get_main_queue();
        __block dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        __block NSInteger count  = 0;
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, sleepTime * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(timer, ^{
            count ++;
            currentTime(count);
        });
        dispatch_resume(timer);
        self.timer = timer;
    
    }
    // 取消定时器
    -(void)cancelTimer {
        if (self.timer) {
            dispatch_source_cancel(self.timer);
        }
    }
    

    相关文章

      网友评论

          本文标题:GCD Timer

          本文链接:https://www.haomeiwen.com/subject/zlcmtctx.html