在非主線程里面使用`NSTimer`創(chuàng)建和取消定時任務(wù)

為什么要在非主線程創(chuàng)建NSTimer

  • 將 timer 添加到主線程的Runloop里面本身會增加線程負荷
  • 如果主線程因為某些原因阻塞卡頓了斤富,timer 定時任務(wù)觸發(fā)的時間精度肯定也會受到影響
  • 有些定時任務(wù)不是UI相關(guān)的锻狗,本來就沒必要在主線程執(zhí)行,給主線程增加不必要的負擔(dān)轻纪。當(dāng)然也可以在定時任務(wù)執(zhí)行時,手動將任務(wù)指派到非主線程上刻帚,但這也是有額外開銷的。

NSTimer的重要特性

  • NSTimer上的定時任務(wù)是在創(chuàng)建NSTimer的線程上執(zhí)行的崇众。NSTimer的銷毀和創(chuàng)建必須在同一個線程上操作
  • NSTimer要被添加到當(dāng)前線程的 Runloop 里面且 Runloop 被啟動航厚,定時任務(wù)(selector或者invocation)才會觸發(fā)。

如何創(chuàng)建NSTimer對象

多數(shù)情況下幔睬,如此一行代碼創(chuàng)建的NSTimer就能正常工作:

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFire) userInfo:nil repeats:YES]

因為這段創(chuàng)建代碼是在主線程里面執(zhí)行的,主線程里面會有系統(tǒng)創(chuàng)建好了的且已經(jīng)啟動了的 Runloop :[NSRunLoop mainRunLoop]麻顶。通過[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]創(chuàng)建時,會自動將創(chuàng)建的NSTimer對象加到當(dāng)前的 Runloop 里面澈蚌,所以 timer 能夠創(chuàng)建后立馬就能工作。

根據(jù)以上宛瞄,可以這么創(chuàng)建自定義線程和運行在上面的 timer :

創(chuàng)建線程對象和NSTimer對象,定義函數(shù)

  • 子類化NSThreadMythread份汗,重載了deallocexit函數(shù),在里面加了 log 輸出杯活,方便跟蹤執(zhí)行過程
    • Mythread.h文件為默認,略去
    • Mythread.m文件:
    #import "Mythread.h"
    
    @implementation Mythread
    
    - (void)dealloc
    {
        NSLog(@"Thread:%p dealloc",self);
    }
    
    + (void)exit
    {
        NSLog(@"Thread:%p exit",self);
        // 注意這是個類函數(shù)
        [super exit];
    }
    
    @end
  • 創(chuàng)建NSThreadNSTimer對象
@property (nonatomic , strong) NSThread *timerThread;
@property (nonatomic , strong) NSTimer *timer;
  • 定義設(shè)置NSTimer的函數(shù)
- (void)createTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFire) userInfo:nil repeats:YES];
    // 創(chuàng)建的線程中旁钧,runloop是不會自己啟動的,需要手動啟動
    [[NSRunLoop currentRunLoop] run];
    NSLog(@"createTimer,currentThread:%@,isMainThread:%@",[NSThread currentThread],@([NSThread isMainThread]));
}
  • 定義self.timer的定時任務(wù)函數(shù)
- (void)timerFire
{
    static NSInteger counter = 0;
    NSLog(@"%@,main:%@,counter:%@",[NSThread currentThread],@([NSThread isMainThread]),@(counter++));
}
  • 定義銷毀self.timer的函數(shù)
- (void)destoryTimerAndThread
{
    NSLog(@"destoryTimerAndThread,currentThread:%@,isMainThread:%@",[NSThread currentThread],@([NSThread isMainThread]));
    [self.timer invalidate];
    @autoreleasepool {
        self.timerThread = nil;
        self.timer = nil;
    }
    // 釋放打開的資源和清空申請的內(nèi)存后歪今,才可以退出颜矿,不然就會內(nèi)存泄露
    [Mythread exit];
}
  • 定義啟動新線程的函數(shù)
- (void)createAndStartThread
{
    NSLog(@"createAndStartThread,currentThread:%@,isMainThread:%@",[NSThread currentThread],@([NSThread isMainThread]));
    self.timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(createTimer) object:nil];
    [self.timerThread start];
}
  • 定義銷毀新線程的函數(shù)
- (void)destoryThread
{
    [self performSelector:@selector(destoryTimer) onThread:self.timerThread withObject:nil waitUntilDone:NO];
}

調(diào)用過程

  1. 主線程中調(diào)用createAndStartThread啟動線程和NSTimer
  2. 隔一小會,主線程中調(diào)用destoryThread銷毀NSTimer和線程
  3. 隔一小會骑疆,主線程中調(diào)用createAndStartThread啟動
  4. 隔一小會,主線程中調(diào)用destoryThread銷毀NSTimer和線程

console輸出結(jié)果

16:16:07.166 : createAndStartThread,currentThread:<NSThread: 0x127d0b750>{number = 1, name = main},isMainThread:1
16:16:08.171 : timerFire,currentThread:<Mythread: 0x127d05810>{number = 2, name = (null)},isMainThread:0,counter:0
16:16:09.173 : timerFire,currentThread:<Mythread: 0x127d05810>{number = 2, name = (null)},isMainThread:0,counter:1
16:16:10.174 : timerFire,currentThread:<Mythread: 0x127d05810>{number = 2, name = (null)},isMainThread:0,counter:2
16:16:11.174 : timerFire,currentThread:<Mythread: 0x127d05810>{number = 2, name = (null)},isMainThread:0,counter:3
16:16:11.479 : destoryTimerAndThread,currentThread:<Mythread: 0x127d05810>{number = 2, name = (null)},isMainThread:0
16:16:11.481 : Thread:0x100011158 exit
16:16:11.482 : Thread:0x127d05810 dealloc
16:16:16.113 : createAndStartThread,currentThread:<NSThread: 0x127d0b750>{number = 1, name = main},isMainThread:1
16:16:17.124 : timerFire,currentThread:<Mythread: 0x127d21700>{number = 3, name = (null)},isMainThread:0,counter:4
16:16:18.124 : timerFire,currentThread:<Mythread: 0x127d21700>{number = 3, name = (null)},isMainThread:0,counter:5
16:16:19.124 : timerFire,currentThread:<Mythread: 0x127d21700>{number = 3, name = (null)},isMainThread:0,counter:6
16:16:20.126 : timerFire,currentThread:<Mythread: 0x127d21700>{number = 3, name = (null)},isMainThread:0,counter:7
16:16:21.126 : timerFire,currentThread:<Mythread: 0x127d21700>{number = 3, name = (null)},isMainThread:0,counter:8
16:16:21.382 : destoryTimerAndThread,currentThread:<Mythread: 0x127d21700>{number = 3, name = (null)},isMainThread:0
16:16:21.383 : Thread:0x100011158 exit
16:16:21.385 : Thread:0x127d21700 dealloc
示例說明
  • 為了節(jié)省顯示空間箍铭,刪除了部分 log 頭信息
  • 創(chuàng)建和銷毀時不一定要在主線程里面調(diào)用,只是為了方便比對輸出結(jié)果
  • 在銷毀 Timer 時诈火,也不一定就要銷毀線程,這里只是演示非主線程的創(chuàng)建和銷毀
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末闸氮,一起剝皮案震驚了整個濱河市剪况,隨后出現(xiàn)的幾起案子蒲跨,更是在濱河造成了極大的恐慌译断,老刑警劉巖或悲,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異巡语,居然都是意外死亡,警方通過查閱死者的電腦和手機男公,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來枢赔,“玉大人,你說我怎么就攤上這事踏拜。” “怎么了速梗?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長姻锁。 經(jīng)常有香客問我,道長屋摔,這世上最難降的妖魔是什么烁设? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任钓试,我火速辦了婚禮副瀑,結(jié)果婚禮上弓熏,老公的妹妹穿的比我還像新娘糠睡。我一直安慰自己挽鞠,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布材义。 她就那樣靜靜地躺著,像睡著了一般嫁赏。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上潦蝇,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天,我揣著相機與錄音攘乒,去河邊找鬼。 笑死则酝,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的沽讹。 我是一名探鬼主播,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼妥泉,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了盲链?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤刽沾,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后侧漓,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡布蔗,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了纵揍。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡泽谨,死狀恐怖特漩,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情涂身,我是刑警寧澤,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布蛤售,位于F島的核電站,受9級特大地震影響陕凹,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜杜耙,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望佑女。 院中可真熱鬧,春花似錦团驱、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽舆蝴。三九已至稚瘾,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背献烦。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工卖词, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人此蜈。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像舶替,于是被迫代替她去往敵國和親令境。 傳聞我的和親對象是個殘疾皇子顾瞪,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,611評論 2 353

推薦閱讀更多精彩內(nèi)容