OC基礎(chǔ)-定時(shí)器

NSTimer實(shí)現(xiàn)定時(shí)器

  • 調(diào)用下面的方法就會(huì)開啟一個(gè)定時(shí)任務(wù)
  + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti
                                       target:(id)aTarget
                                     selector:(SEL)aSelector
                                     userInfo:(id)userInfo
                                      repeats:(BOOL)yesOrNo;
  • 每隔ti秒,調(diào)用一次aTarget的aSelector方法,
  • yesOrNo決定了是否重復(fù)執(zhí)行這個(gè)任務(wù)
  • 通過invalidate方法可以停止定時(shí)器的工作
  - (void)invalidate;
  • 一旦定時(shí)器被停止了,就不能再次執(zhí)行任務(wù)
  • 只能再次創(chuàng)建一個(gè)新的定時(shí)器才能執(zhí)行新的任務(wù)

GCD定時(shí)器

  • 創(chuàng)建GCD定時(shí)器dispatch_source_t,可以直接敲dispatch_source timer就能看到一個(gè)創(chuàng)建GCD定時(shí)器的函數(shù),會(huì)自動(dòng)生成創(chuàng)建代碼塊

    // 創(chuàng)建定時(shí)器
    // 第1個(gè)參數(shù):資源的類型
    // 第2個(gè)參數(shù):函數(shù)句柄,一般不需要,直接傳0
    // 第3個(gè)參數(shù):直接傳0
    // 第4個(gè)參數(shù):任務(wù)的執(zhí)行隊(duì)列,如果是并發(fā)隊(duì)列,這個(gè)方法內(nèi)部會(huì)開新線程
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatchQueue);
    
    // 設(shè)置定時(shí)器什么時(shí)候開始,每隔多久執(zhí)行一次
    // 第2個(gè)參數(shù):什么時(shí)候開始,dispatch_time_t類型
    // 第3個(gè)參數(shù):每隔多久執(zhí)行一次,單位是納秒(1s = 10的9次方ns)
    // 第4個(gè)參數(shù):leewayInSeconds字面意思是回旋的秒數(shù),一般傳0就可以了,單位是納秒
    // NSEC_PER_SEC表示1秒所含的納秒數(shù),在下面關(guān)鍵詞解釋有說明
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, intervalInSeconds * NSEC_PER_SEC, leewayInSeconds * NSEC_PER_SEC);
    
    // 定時(shí)器要執(zhí)行的任務(wù)
    dispatch_source_set_event_handler(timer, ^{
        // 代碼邏輯
    });
    
    // 取消定時(shí)器時(shí)要執(zhí)行的任務(wù)
    dispatch_source_set_cancel_handler(timer, ^{
        // 代碼邏輯
    });
    
    // 啟動(dòng)定時(shí)器
    dispatch_resume(timer);
    
  • 一個(gè)完整的定時(shí)器的實(shí)現(xiàn)邏輯

    @interface ViewController ()
    /** 定時(shí)器(這里不用帶*,因?yàn)閐ispatch_source_t就是個(gè)類,內(nèi)部已經(jīng)包含了*) */
    @property (nonatomic, strong) dispatch_source_t timer;
    @end
    
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        [self gcdTimerTest];
    }
    
    // 創(chuàng)建GCD定時(shí)器
    -(void)gcdTimerTest
    {
        // 設(shè)定定時(shí)器延遲3秒開始執(zhí)行
        dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));
        // 每隔2秒執(zhí)行一次
        uint64_t interval = (uint64_t)(2.0 * NSEC_PER_SEC);
        dispatch_source_set_timer(self.timer, start, interval, 0);
    
        // 要執(zhí)行的任務(wù)
        dispatch_source_set_event_handler(self.timer, ^{
            NSLog(@"%s",__func__);
        });
    
        // 啟動(dòng)定時(shí)器
        dispatch_resume(self.timer);
    }
    
    - (dispatch_source_t)timer
    {
        if(_timer == nil)
        {
            // 創(chuàng)建隊(duì)列
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            // dispatch_source_t,【本質(zhì)還是個(gè)OC對(duì)象】
            _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        }
    
        return _timer;
    }
    
  • 取消定時(shí)器

    // 停止定時(shí)器
    dispatch_cancel(self.timer);
    

NSTimer和GCD器的定時(shí)區(qū)別

  • NSTimer是在RunLoop中以特定Mode運(yùn)行的,由于RunLoop中要處理各種事件,所以導(dǎo)致NSTimer并不是很精確
  • GCD定時(shí)器不受RunLoop的Mode的影響,從時(shí)間精確到了納秒看,這種定時(shí)器是非常精確的,深受開發(fā)者的喜愛

關(guān)鍵詞解釋

  • SEC:秒(s)
  • MSEC:毫秒(ms)
  • USEC:微妙(μs)
  • NSEC:納秒(ns)
  • PER:每
  • 換算關(guān)系
    • 1秒(s)=1000 毫秒(ms)
    • 1毫秒(ms)=1000 微秒(μs)
    • 1微秒(μs)=1000 納秒(ns)
  • 宏定義解釋
// 1s = 1000000000ns
#define NSEC_PER_SEC  1000000000ull
// 1ms = 1000000ns
#define NSEC_PER_MSEC 1000000ull
// 1μs = 1000ns
#define NSEC_PER_USEC 1000ull
// 1s = 1000000μs
#define USEC_PER_SEC  1000000ull
  • 延時(shí)1秒的寫法,注意第二個(gè)參數(shù)的單位是納秒
// 推薦
dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);

// 將微秒轉(zhuǎn)換成納秒(知道就行,一般開發(fā)不這么寫)
dispatch_time(DISPATCH_TIME_NOW, 1000000 * NSEC_PER_USEC);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容