#import <Foundation/Foundation.h>
typedef void(^TimerBlock)(void);
@interface SFTimer :NSObject
+ (instancetype)sharedInstance;
/**
CGD定时器 回调方法在 主线程 中执行
@param interval 定时间隔
@param timerBlcok 回调
*/
- (void)startGCDTimerOnMainQueueWithInterval:(int)interval Blcok:(TimerBlock)timerBlcok;
/**
CGD定时器 回调方法在 子线程 中执行
@param interval 定时间隔
@param timerBlcol 回调
*/
- (void)startGCDTimerOnGlobalQueueWithInterval:(int)interval Blcok:(TimerBlock)timerBlcol;
/** 停止定时器 */
- (void)stopGCDTimer;
@end
#import "SFTimer.h"
dispatch_source_t timer;
@implementation SFTimer
+ (instancetype)sharedInstance
{
static dispatch_once_t __once_t;
static id __singleon__;
dispatch_once(&__once_t, ^{
__singleon__ = [[self alloc] init];
});
return __singleon__;
}
- (void)startGCDTimerOnGlobalQueueWithInterval:(int)interval Blcok:(TimerBlock)timerBlcok {
if(!interval) {
interval =1;
}
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(timer, ^{
if(timerBlcok) {
timerBlcok();
}
});
// 开启定时器
dispatch_resume(timer);
}
- (void)startGCDTimerOnMainQueueWithInterval:(int)interval Blcok:(TimerBlock)timerBlcok {
if(!interval) {
interval =1;
}
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(timer, ^{
dispatch_async(dispatch_get_main_queue(), ^{
if(timerBlcok) {
timerBlcok();
}
});
});
// 开启定时器
dispatch_resume(timer);
}
- (void)stopGCDTimer {
if(timer){
dispatch_source_cancel(timer);
}
}
- (void)dealloc
{
[self stopGCDTimer];
}
@end
@end
网友评论