GCDTimer

作者: Codepgq | 来源:发表于2017-06-30 17:33 被阅读101次
    #import <Foundation/Foundation.h>
    
    @interface PQTimer : NSObject
    
    /**
     创建一个定时器
    
     @param time 多少秒运行一次
     @param beginTime 开始时间
     @param complete 回调 在回调中如果返回 YES 会停止计时 返回 NO 继续执行
     @return 对象
     */
    + (PQTimer*)timerWithTimeInterval:(NSTimeInterval)time beginTime:(NSTimeInterval)beginTime complete:(BOOL(^)())complete;
    
    - (void)stopTimer;
    - (void)satrtTimer;
    @end
    
    

    .m

    #import "PQTimer.h"
    
    @interface PQTimer ()
    
    @property (nonatomic, strong) dispatch_source_t time;
    
    @end
    
    @implementation PQTimer
    
    + (PQTimer*)timerWithTimeInterval:(NSTimeInterval)time beginTime:(NSTimeInterval)beginTime complete:(BOOL(^)())complete{
        PQTimer * timer = [[PQTimer alloc] init];
        //获得队列
        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        //创建一个定时器
        timer.time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        //设置开始时间
        dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(beginTime * NSEC_PER_SEC));
        //设置时间间隔
        uint64_t interval = (uint64_t)(time * NSEC_PER_SEC);
        //设置定时器
        dispatch_source_set_timer(timer.time, start, interval, 0);
        //设置回调
        dispatch_source_set_event_handler(timer.time, ^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                BOOL isStop = complete();
                if (isStop) {
                    dispatch_source_cancel(timer.time);
                }
            });
            
        });
        //由于定时器默认是暂停的所以我们启动一下
        //启动定时器
        dispatch_resume(timer.time);
        return timer;
    }
    
    - (void)stopTimer{
            dispatch_resume(self.time);
        dispatch_source_cancel(self.time);
    }
    
    
    - (void)satrtTimer{
        dispatch_resume(self.time);
    }
    
    //这里用于暂停定时器,但是需要注意的是暂停之后不能调用停止定时器的方法,会crash,如果想调用应该先resume定时器,在销毁
    - (void)pauseTimer{//挂起之后无法被销毁
        dispatch_suspend(self.time);
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:GCDTimer

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