使用NSTimer在ios中启动NSThread



我需要每10分钟左右安排一次后台操作。该操作包括从核心数据中收集对象,并将其信息上传到Web服务,以避免以任何方式更改它们。

我正在考虑的方法是创建一个nstimer应用内代理,每10分钟启动一次。这将触发NSThread,NSThread将在后台运行操作,不会对用户造成任何干扰。线程正常退出后会在这里。

我一直在研究启动一个线程,并在每次执行操作后将其设置为睡眠,但计时器方法似乎是最干净的。

网上的另一个建议是使用运行循环,但我看不出在这种特定情况下的使用。

有人有什么建议或想告诉他们如何应对类似的情况吗。

问候

计时器听起来是真正启动线程的正确方法。要设置它,只需将其放在您的应用程序代理中即可

[NSSTimer scheduledTimerWithTimeInterval:60.0 * 10.0 target:self selector:@selector(startBackgroundMethod) userInfo:nil repeats:YES];

然后创建这样的背景方法代码:

- (void)startBackgroundMethod
{
    //the timer calls this method runs on the main thread, so don't do any
    //significant work here. the call below kicks off the actual background thread
    [self performSelectorInBackground:@selector(backgroundMethod) withObject:nil];
}
- (void)backgroundMethod
{
    @autoreleasepool
    {
        //this runs in a  background thread, be careful not to do any UI updates
        //or interact with any methods that run on the main thread
        //without wrapping them with performSelectorOnMainThread:
    }
}

至于是否真的有必要在后台线程中完成这项工作,这取决于它是什么。除非由于并发错误的可能性而被严格要求,否则应该避免线程,所以如果你告诉我们你的线程将要做什么,我们可以建议基于运行循环的方法是否更合适。

最新更新