定時器分為三種:1、NSTimer? ? ? 2、CADisplayLink ? ?3、GCD實現
今天著重學習一下GCD中的定時器實現方法
因為簡單,直接貼代碼:
#pragma mark -定時器
- (void)gcdTimer
{
//get the queue
dispatch_queue_t queue = dispatch_queue_create(0,0);
//create timer
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
//set begining time
dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0*NSEC_PER_SEC));
//set the interver
uint64_t interver = (uint64_t)(1.0*NSEC_PER_SEC);
dispatch_source_set_timer(self.timer, start, interver,0.0);
dispatch_source_set_event_handler(self.timer, ^{
dispatch_async(dispatch_get_global_queue(0,0), ^{
self.currentNum++;
NSLog(@"%li",self.currentNum);
if(self.currentNum >= MaxNum) {
//關閉定時器
dispatch_source_cancel(self.timer);
}
});
});
//開啟定時器
dispatch_resume(self.timer);
}
1、dispatch_source_set_event_handler()中的任務實在子線程中執行的,若需要回到主線程,要調用dispatch_async(dispatch_get_main_queue(), ^{}。
2、dispatch_source_set_timer中第二個參數,當我們使用dispatch_time或者DISPATCH_TIME_NOW時,系統會使用默認時鐘來進行計時。然而當系統休眠的時候,默認時鐘是不走的,也就會導致計時器停止。使用dispatch_walltime可以讓計時器按照真實時間間隔進行計時。
3、第三個參數,1.0 * NSEC_PER_SEC為每秒執行一次,對應的還有毫秒,分秒,納秒可以選擇。
①、dispatch_source_set_event_handler這個函數在執行完之后,block 會立馬執行一遍,后面隔一定時間間隔再執行一次。而NSTimer第一次執行是到計時器觸發之后。這也是和NSTimer之間的一個顯著區別。
②、掛起(暫停)定時器,dispatch_suspend之后的Timer,不能被釋放的,會引起崩潰.
③、創建的timer一定要有dispatch_suspend(_timer)或dispatch_source_cancel(_timer)這兩句話來指定出口,否則定時器將不執行,若我們想無限循環可將dispatch_source_cancel(_timer)寫在一句永不執行的if判斷語句中。