定時器分為三種:1糠聪、NSTimer? ? ? 2、CADisplayLink ? ?3、GCD實現(xiàn)
今天著重學(xué)習(xí)一下GCD中的定時器實現(xiàn)方法
因為簡單傲隶,直接貼代碼:
#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) {
//關(guān)閉定時器
dispatch_source_cancel(self.timer);
}
});
});
//開啟定時器
dispatch_resume(self.timer);
}
1、dispatch_source_set_event_handler()中的任務(wù)實在子線程中執(zhí)行的胧瓜,若需要回到主線程矢棚,要調(diào)用dispatch_async(dispatch_get_main_queue(), ^{}。
2府喳、dispatch_source_set_timer中第二個參數(shù)蒲肋,當(dāng)我們使用dispatch_time或者DISPATCH_TIME_NOW時,系統(tǒng)會使用默認時鐘來進行計時钝满。然而當(dāng)系統(tǒng)休眠的時候兜粘,默認時鐘是不走的,也就會導(dǎo)致計時器停止弯蚜。使用dispatch_walltime可以讓計時器按照真實時間間隔進行計時孔轴。
3、第三個參數(shù)碎捺,1.0 * NSEC_PER_SEC為每秒執(zhí)行一次路鹰,對應(yīng)的還有毫秒,分秒收厨,納秒可以選擇晋柱。
①、dispatch_source_set_event_handler這個函數(shù)在執(zhí)行完之后诵叁,block 會立馬執(zhí)行一遍雁竞,后面隔一定時間間隔再執(zhí)行一次。而NSTimer第一次執(zhí)行是到計時器觸發(fā)之后拧额。這也是和NSTimer之間的一個顯著區(qū)別碑诉。
②、掛起(暫停)定時器,dispatch_suspend之后的Timer势腮,不能被釋放的,會引起崩潰.
③联贩、創(chuàng)建的timer一定要有dispatch_suspend(_timer)或dispatch_source_cancel(_timer)這兩句話來指定出口,否則定時器將不執(zhí)行捎拯,若我們想無限循環(huán)可將dispatch_source_cancel(_timer)寫在一句永不執(zhí)行的if判斷語句中泪幌。