GCD定时器封装
简单调用
[ZFTimer execTask:^{
NSLog(@"1111111 - %@",[NSThread currentThread]);
}start:2 interval:1 repeats:YES async:YES];
@interface ZFTimer : NSObject
/// 启动定时器
/// @param task 任务
/// @param start 开始时间
/// @param interval 重复时间间隔
/// @param repeats 是否重复
/// @param async 是否异步
+ (NSString*)execTask:(void(^)(void))taskstart:(NSTimeInterval)startinterval:(NSTimeInterval)intervalrepeats:(BOOL)repeatsasync:(BOOL)async;
+ (NSString*)execTask:(id)targetselector:(SEL)selectorstart:(NSTimeInterval)startinterval:(NSTimeInterval)intervalrepeats:(BOOL)repeatsasync:(BOOL)async;
/// 取消定时器
/// @paramname 定时器标识
+ (void)cancelTask:(NSString*)name;
@end
@implementation ZFTimer
static NSMutableDictionary *times;
dispatch_semaphore_t semaphore;
+ (void)initialize {
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
times = [NSMutableDictionary dictionary];
semaphore = dispatch_semaphore_create(1);
});
}
+ (NSString*)execTask:(void(^)(void))taskstart:(NSTimeInterval)startinterval:(NSTimeInterval)intervalrepeats:(BOOL)repeatsasync:(BOOL)async {
if(!task) {
returnnil;
}
//队列
dispatch_queue_t queue = async ? dispatch_get_global_queue(0, 0) : dispatch_get_main_queue();
//创建定时器
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
//设置时间
dispatch_source_set_timer(timer,dispatch_time(DISPATCH_TIME_NOW, start *NSEC_PER_SEC), interval *NSEC_PER_SEC,0);
//加锁
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//定时器的唯一标识
NSString*name = [NSStringstringWithFormat:@"%zd",times.count];
//存放到字典中
[timessetObject:timerforKey:name];
dispatch_semaphore_signal(semaphore);
//设置回调
dispatch_source_set_event_handler(timer, ^{
task();
if(!repeats) {//不重复的任务
[selfcancelTask:name];
}
});
//启动定时器
dispatch_resume(timer);
returnname;
}
+ (NSString*)execTask:(id)targetselector:(SEL)selectorstart:(NSTimeInterval)startinterval:(NSTimeInterval)intervalrepeats:(BOOL)repeatsasync:(BOOL)async {
if(!target || !selector) {
returnnil;
}
return[selfexecTask:^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
if([targetrespondsToSelector:selector]) {
[targetperformSelector:selector];
}
#pragma clang diagnostic pop
}start:startinterval:intervalrepeats:repeatsasync:async];
}
+ (void)cancelTask:(NSString*)name {
if(name.length==0) {
return;
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_source_ttimer =times[name];
if(timer) {
dispatch_source_cancel(timer);
[times removeObjectForKey:name];
}
dispatch_semaphore_signal(semaphore);
}
@end