我正在尝试在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秒注册一次该服务即可。根据通过的分钟数,我可以选择是通过网络检查某些信息,还是做一些有趣的业务。
接下来的问题是,在fetch api上指定60秒的间隔是否真的能保证每60秒更新一次?或者会有明显的漂移吗?