计时器在Objective-C中的另一个线程中 [英] Timer in another thread in Objective - C

查看:55
本文介绍了计时器在Objective-C中的另一个线程中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须定义应在一定时间间隔内定期调用的方法.我需要在另一个线程(不是主线程)中调用它,因为此方法用于从外部API获取信息并同步核心数据中的数据.

I have to define method which should be invoked periodically with some time interval. I need to invoke it in another thread (NOT main thread), because this method is used to get information from external API and sync data in core data.

我如何定义此方法以不阻塞主线程?

How do I define this method to not block main thread?

推荐答案

除非您特别需要计时器,否则可以使用Grand Central Dispatch.

Unless you have a specific need for timers, you can use Grand Central Dispatch.

以下代码段将在2秒后在默认优先级并发队列(即后台线程)上执行一个块.如果您认为合适,可以更改队列的优先级,但是除非您要在并发队列上处理许多不同的操作,否则默认设置就足够了.

The following snippet will execute a block after 2 seconds, on the default priority concurrent queue (i.e a background thread). You can change the priority of the queue if you see fit, but unless you're dealing with lots of different operations on concurrent queues, default will suffice.

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 设置重复执行.其主要内容如下:

If you're wanting to call this repeatedly, then you can use dispatch_source_set_timer to set a recurring execution. The jist of it is below:

// 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);

这篇关于计时器在Objective-C中的另一个线程中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆