多线程定时器

时间:2021-01-30 23:19:04

多线程定时器====

-(void)testGCDTime
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//创建一个定时起源
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

//设置回调时间间隔
int64_t interval = (int64_t)(1 * NSEC_PER_SEC);
//设置定时器开始时间
dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC));

//启动计时器
//参数1:timer
//参数2:开始时间
//参数3:时间间隔
//参数4:0
dispatch_source_set_timer(source, start, interval, 0);

//设置回调事件,即每次定时器触发的处理时间
dispatch_source_set_event_handler(source, ^{
static int number = 0;
NSLog(@"%d", number);

number++;
//运行到第6秒则取消计时器
if (number == 6) {
dispatch_source_cancel(source);
NSLog(@"Cancle timer.");
}
});

//启动定时器
dispatch_resume(source);
}