1

我正在尝试在 iOS7 中实现一个长时间运行的类似 cron 的后台任务。我现在的工作方式是一个重复计时器,它以小于 10 分钟的频率运行,然后以预定义的时间间隔启动和停止 locationManager 的 startUpdatingLocation:

/*
 * Very important, this function is called once a minute in the background and it specifies what          actions to take based on the number of minutes passed.
 */
-(void)everyMinuteAction
{
    NSLog(@"Every minute action");
    if ([_killTime timeIntervalSinceNow] < 0.0)
    {
        //App is dead, long live the app!
        _appKilledDueToInactivity = YES;

        //Do some stuff to indicate to the user on the UI that they should not


    }

    //Once every n minutes, we need to turn on the GPS and report our location with four points.
    NSLog(@"Modulus: %d", numberOfMinutesPassedSinceAppStarted % (int)floor((double)currentTTL/60.0));

    if ((numberOfMinutesPassedSinceAppStarted % (int)floor((double)currentTTL/60.0) == 0) || numberOfMinutesPassedSinceAppStarted == 0)
    {
        //Treat it differently if we are in foreground or background
        //GPS only responds with locations quickly when in foreground, so give it a bit more time if it is in the background.
        if (inBackground)
        {
            [NSTimer scheduledTimerWithTimeInterval:140 target:self selector:@selector(killGPSAfterCertainTime) userInfo:nil repeats:NO];
        } else {
            //Start a timer that will kill the GPS after a certain period of time, regardless of how many points it has.
        [NSTimer scheduledTimerWithTimeInterval:80 target:self selector:@selector(killGPSAfterCertainTime) userInfo:nil repeats:NO];
        }




        [self.locationManager startUpdatingLocation];

        //Control is now passed on to didUpdateLocations, which will turn off location tracking after either a set period of time or a set number of
        //locations received.

        self.timeSpentFartassingAroundTryingToGetLocations = [[NSDate alloc] init];
        self.numberOfLocationsCollectedThisTTL = 0;
    }

    if (3 % numberOfMinutesPassedSinceAppStarted == 0)
    {
        //Every 3 minutes we need to do some talking to the server
    }


    //Increment this, we've been using the app for another minute.
    numberOfMinutesPassedSinceAppStarted += 1;
}

事实证明,如果 TTL 大于 10 分钟,这会在 10 分钟后被杀死,而且我也不完全确定它是否适用于我的 plist 文件中启用的后台位置权限。

我想知道我是否能够使用新的获取网络信息后台任务来实现这一点 - 只需更改方法的签名并每 60 秒注册一次该服务即可。根据经过的分钟数,我可以选择是通过网络检查一些信息,还是做一些 gps 有趣的事情。

下一个问题是在 fetch api 上指定 60 秒的时间间隔是否真的能保证我每 60 秒更新一次?还是会有明显的漂移?

4

0 回答 0