GCD中使用dispatch_after函數延遲處理任務


在實際的開發中,經常會遇到想要在指定的時間間隔后執行某個處理

<一>在GCD中提供了dispatch_after函數來完成這一操作

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        <#code to be executed after a specified delay#>

    });

其中(int64_t)(<#delayInSeconds#> * NSEC_PER_SEC) 返回的是時間間隔,數值與 NSEC_PER_SEC的乘積返回毫微秒的數值,

 

#define NSEC_PER_SEC 1000000000ull 秒

#define NSEC_PER_MSEC 1000000ull 

#define USEC_PER_SEC 1000000ull

#define NSEC_PER_USEC 1000ull

<注意點>因為Main Dishpatch Queue在主線程的RunLoop中執行,所以比如在每隔1/60秒執行的RunLoop中,Block最快在三秒后執行,最慢在3秒+1/60秒后執行,並且在Main Dispatch Queue有大量追加處理貨主線程本身的任務處理有延遲時,這個時間會增加

dispatch_time函數能獲得從指定時間開始到第二個參數指定的時間間隔后的時間.

<二>補充,NSObject中提供的線程延遲方法

[self performSelector:@selector(run) withObject:nil afterDelay:2.0];

<三>通過NSTimer來延遲線程執行

[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:NO];


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM