dispatch_source_t实现定时器
1 @interface ViewController () 2 3 @property (nonatomic, strong) dispatch_source_t timer; 4 5 @end
以上ViewController持有一个dispatch_source_t,注意:(如果dispatch_source_t未持有,它会因为被内存回收掉,导致handler回调无法执行)
- (void)viewDidLoad { [super viewDidLoad]; __block int count = 3; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(timer, dispatch_walltime(NULL, 2.0*NSEC_PER_SEC), 2.0*NSEC_PER_SEC, 0); dispatch_source_set_event_handler(timer, ^{ if (count==0) { dispatch_source_cancel(timer); return; } count --; NSLog(@"--------"); }); dispatch_source_set_cancel_handler(timer, ^{ NSLog(@"=====cancel"); }); dispatch_resume(timer); self.timer = timer; }
1.dispatch_source_create
创建一个新的调度源来监视低级别的系统对象和自动提交处理程序块来响应事件调度队列
2.dispatch_source_set_timer
为一个定时源设置一个开始时间、事件间隔、误差值
void dispatch_source_set_timer(dispatch_source_t source, dispatch_time_t start,//开始执行时间,0或DISPATCH_TIME_NOW:立即执行(纳秒)
uint64_t interval,//循环执行间隔,纳秒
uint64_t leeway);//误差值,这里如果设置0,表示非常精准的执行定时器
注意:这里设置的时间单位都是纳秒,其中NSEC_PER_SEC代表每秒钟对应的纳秒数
其中start参数可以是:dispatch_time或dispatch_walltime,关于它们的区别参考如下:
dispatch_time stops running when your computer goes to sleep. dispatch_walltime continues running. So if you want to do an action in one hour minutes, but after 5 minutes your computer goes to sleep for 50 minutes, dispatch_walltime will execute an hour from now, 5 minutes after the computer wakes up. dispatch_time will execute after the computer is running for an hour, that is 55 minutes after it wakes up.
大概意思就是在电脑进入休眠状态后,dispatch_time的将要停止执行,而dispatch_walltime将继续执行。
3.dispatch_source_set_event_handler
给一个调度源设置一个时间处理块。(即定时器回调处理块)
4.dispatch_source_cancel
取消一个调度源
5.dispatch_source_set_cancel_handler
给一个调度源设置一个取消处理块
6.dispatch_resume
开始一个调度器
要得到你必须要付出,要付出你还要学会坚持,如果你真的觉得很难,那你就放弃,但是你放弃了就不要抱怨,我觉得人生就是这样,世界真的是平等的,每个人都要通过自己的努力,去决定自己生活的样子。