设备锁定时后台任务停止?

Ton*_*Law 7 nstimer ios appdelegate ios8.3

当设备进入后台时,我有一个计时器正在运行,因为我想检查我服务中的少量数据.我在app delegate中的applicationDidEnterBackground方法中使用以下代码

    UIApplication *app = [UIApplication sharedApplication];

//create new uiBackgroundTask
__block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];

//and create new timer with async call:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //run function methodRunAfterBackground
    NSString *server = [variableStore sharedGlobalData].server;
    NSLog(@"%@",server);
    if([server isEqual:@"_DEV"]){
        arrivalsTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(getArrivals) userInfo:nil repeats:YES];
    }
    else {
        arrivalsTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(getArrivals) userInfo:nil repeats:YES];
    }
    [[NSRunLoop currentRunLoop] addTimer:arrivalsTimer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
});
Run Code Online (Sandbox Code Playgroud)

这工作绝对正常,直到设备自动锁定,然后计时器停止滴答.有关如何阻止这种情况发生的任何建议?默认的实时时间是5分钟,因此大多数设备将在此偶数之前锁定一次.

谢谢

Rob*_*Rob 4

一些观察结果:

  1. 正如 H 先生指出的,beginBackgroundTaskWithExpirationHandler在当代 iOS 版本中只给你 30 秒(之前是 3 分钟)。因此,尝试在五分钟内启动计时器是行不通的。

    您可以用来[[UIApplication sharedApplication] backgroundTimeRemaining]查询您还剩多少时间。

  2. 当设备锁定时,后台任务将继续。您不应该看到应用程序终止。如果用户通过“双击主页按钮并在任务切换器屏幕上向上滑动”手动终止应用程序,这将杀死后台任务,但不仅仅是锁定设备。

  3. 关于定时器的一些评论:

    • 该代码将计时器添加到后台队列。这一般是没有必要的。仅仅因为应用程序处于后台状态,您仍然可以继续使用计时器等的主运行循环。

      因此,只需scheduledTimerWithTimeInterval从主线程调用即可完成。除非绝对必要,否则使用带有运行循环的 GCD 工作线程是没有意义的(即使如此,我也可能创建自己的线程并向其添加运行循环)。

      顺便说一句,如果绝对有必要在某些后台调度队列上调度计时器,那么使用调度计时器可能会更容易。它完全消除了运行循环的要求。

    • 顺便说一句,它不适合与scheduledTimerWithTimeInterval一起使用addTimer。您调用scheduledTimerWithTimeInterval创建一个计时器并将其添加到当前运行循环中。如果您想将其添加到另一个运行循环,请使用timerWithTimeInterval然后调用。addTimer