#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface LITimer_GCD : NSObject
+(NSString *)execTask:(void(^)(void))task;
+(NSString *)execTask:(void(^)(void))task
start:(NSTimeInterval)start
interval:(NSTimeInterval)interval
repeats:(BOOL)repeatsasync:(BOOL)async;
+(void)cancleTask:(NSString *)taskName;
@end
NS_ASSUME_NONNULL_END
================================================.m文件
#import "LITimer_GCD.h"
@implementation LITimer_GCD
static NSMutableDictionary *timers;
dispatch_semaphore_t semaphore_;
+(void)initialize
{
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
timers = [[NSMutableDictionary alloc] init];
semaphore_ = dispatch_semaphore_create(1);
});
}
+(NSString*)execTask:(void(^)(void))task
{
return [self execTask:task start:0 interval:1 repeats:YES async:NO];
}
+(NSString*)execTask:(void(^)(void))taskstart:(NSTimeInterval)startinterval:(NSTimeInterval)intervalrepeats:(BOOL)repeatsasync:(BOOL)async
{
if(!task || start <0|| (interval <=0&& repeats)) {
returnnil;
}
//创建队列
dispatch_queue_t queue = async ? dispatch_queue_create("timer", DISPATCH_QUEUE_SERIAL) : 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 = [NSString stringWithFormat:@"%lu",(unsigned long)timers.count];
timers[name] = timer;
//解锁
dispatch_semaphore_signal(semaphore_);
//设置回调
dispatch_source_set_event_handler(timer, ^{
task();
if(!repeats){
[selfcancleTask:name];
}
});
//启动定时器
dispatch_resume(timer);
returnname;
}
+(void)cancleTask:(NSString*)taskName
{
if(taskName.length<=0) {
return;
}
dispatch_source_ttimer =timers[taskName];
if(!timer){
return;
}
//加锁
dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
dispatch_source_cancel(timer);
[timers removeObjectForKey:taskName];
dispatch_semaphore_signal(semaphore_);
}
@end
网友评论