GCD-定時器

定時器分為三種: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判斷語句中。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • /** 定時器(這里不用帶*,因為dispatch_source_t就是個類,內部已經包含了*) */ @prop...
    CocoaJason閱讀 778評論 0 0
  • GCD定時器不受RunLoop影響,比NSTimer更精確 //獲得隊列 //dispatch_queue_t q...
    rlqs閱讀 434評論 0 0
  • 提到定時器,NStimer肯定是我們最為熟悉的。 但是NStimer有著很大的缺點,并不準確。 通俗點說,就是它該...
    mengyingguo閱讀 385評論 0 0
  • //獲得隊列 dispatch_queue_t queue = dispatch_get_global_queue...
    HsuKit閱讀 206評論 0 0
  • #import"ViewController.h" NSInteger count=0; @interfaceVi...
    清蘂翅膀的技術閱讀 813評論 0 0