簡體   English   中英

在Objective - C中的另一個線程中的計時器

[英]Timer in another thread in Objective - C

我必須定義應該以一定的時間間隔定期調用的方法。 我需要在另一個線程(非主線程)中調用它,因為此方法用於從外部API獲取信息並在核心數據中同步數據。

如何定義此方法以阻止主線程?

除非您特別需要計時器,否則您可以使用Grand Central Dispatch。

以下代碼段將在默認優先級並發隊列(即后台線程)上2秒后執行一個塊。 如果認為合適,可以更改隊列的優先級,但除非您在並發隊列上處理大量不同的操作,否則默認就足夠了。

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));

dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    // Your code here
});

如果您想重復調用它,則可以使用dispatch_source_set_timer設置重復執行。 它的主旨如下:

// Create a dispatch source that'll act as a timer on the concurrent queue
// You'll need to store this somewhere so you can suspend and remove it later on
dispatch_source_t dispatchSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
                                                          dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); 

// Setup params for creation of a recurring timer
double interval = 2.0;
dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW, 0);
uint64_t intervalTime = (int64_t)(interval * NSEC_PER_SEC);
dispatch_source_set_timer(dispatchSource, startTime, intervalTime, 0);

// Attach the block you want to run on the timer fire
dispatch_source_set_event_handler(dispatchSource, ^{
    // Your code here
});

// Start the timer
dispatch_resume(dispatchSource);

// ----

// When you want to stop the timer, you need to suspend the source
dispatch_suspend(dispatchSource);

// If on iOS5 and/or using MRC, you'll need to release the source too
dispatch_release(dispatchSource);

使用NSRunLoop和NSTimer進行工作

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer) userInfo:nil repeats:NO];

[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM