2010-09-16 127 views
2

在我的iPhone应用程序中,我有一个后台任务,在应用程序进入后台状态时开始运行。 该任务运行良好,并且以这样的循环结构化:iPhone后台任务在某个时间点停止运行

运行。 睡5分钟。 运行。 睡5分钟。

出于某种原因,该任务将停止一定时间后运行......说半小时到一小时。

任何人都可以帮我理解为什么吗? 这里是后台任务代码:

- (void)applicationDidEnterBackground:(UIApplication *)application {  
NSLog(@"Application entered background state."); 

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"bgCheckSwitch"] == YES) { 

    //UIApplication* app = [UIApplication sharedApplication]; 



    // Request permission to run in the background. Provide an 

    // expiration handler in case the task runs long. 

    NSAssert(bgTask == UIBackgroundTaskInvalid, nil); 



    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ 

     // Synchronize the cleanup call on the main thread in case 

     // the task actually finishes at around the same time. 

     dispatch_async(dispatch_get_main_queue(), ^{ 

      if (bgTask != UIBackgroundTaskInvalid) 

      { 

       [application endBackgroundTask:bgTask]; 

       bgTask = UIBackgroundTaskInvalid; 

      } 

     }); 

    }]; 



    // Start the long-running task and return immediately. 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 



     // Do the work associated with the task. 

     [someClass doSomeThing]; //The actual method performed by the task. The looping is in the method. 


     dispatch_async(dispatch_get_main_queue(), ^{ 

      if (bgTask != UIBackgroundTaskInvalid) 

      { 

       [application endBackgroundTask:bgTask]; 

       bgTask = UIBackgroundTaskInvalid; 

      } 

     }); 

    }); 


} 

} 
+0

您的后台任务如何运行一个小时?使用类似的代码我的任务在一分钟后死亡。基本上它只是一个非重复的计时器。你如何实现“睡5分钟”? - 谢谢 – Dimitris 2010-10-18 09:30:17

回答

2

后台任务只运行了一段时间,那么OS杀死它。这在多任务处理WWDC10视频中进行了讨论。

+0

我认为你总共有5分钟的处理时间来完成任务。这可能会在IOS – Petesh 2010-09-16 09:23:28

+0

的后续修订中得到提高,我忘记了,但我认为这是10分钟。我知道这些视频告诉你。 – jer 2010-09-16 09:24:12

+0

这可能很方便:http://stackoverflow.com/questions/3388279/iphone-task-completion – Petesh 2010-09-16 09:25:01