GCDTimer

#import <Foundation/Foundation.h>

@interface PQTimer : NSObject

/**
 創(chuàng)建一個定時器

 @param time 多少秒運行一次
 @param beginTime 開始時間
 @param complete 回調(diào) 在回調(diào)中如果返回 YES 會停止計時 返回 NO 繼續(xù)執(zhí)行
 @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);
    //創(chuàng)建一個定時器
    timer.time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //設(shè)置開始時間
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(beginTime * NSEC_PER_SEC));
    //設(shè)置時間間隔
    uint64_t interval = (uint64_t)(time * NSEC_PER_SEC);
    //設(shè)置定時器
    dispatch_source_set_timer(timer.time, start, interval, 0);
    //設(shè)置回調(diào)
    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);
}

//這里用于暫停定時器,但是需要注意的是暫停之后不能調(diào)用停止定時器的方法,會crash,如果想調(diào)用應(yīng)該先resume定時器,在銷毀
- (void)pauseTimer{//掛起之后無法被銷毀
    dispatch_suspend(self.time);
}

@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容