iOS的几种定时器

时间:2024-10-26 23:37:26
//gcd的定时器timer必须先保存为一个属性或者成员变量
@property (nonatomic , assign) dispatch_source_t timer; //第一种 每一秒执行一次(重复性)
double delayInSeconds = 1.0; //每间隔1秒执行
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC, 0.0);
dispatch_source_set_event_handler(timer, ^{
NSLog(@"timer date 1== %@",[NSDate date]);
});
dispatch_resume(timer); //第二种 二秒后执行 (一次性)
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSLog(@"timer date 2== %@",[NSDate date]);
}); //第三种 每一秒执行一次 (重复性)
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(testTimer) userInfo:nil repeats:YES];