title: Repeating a task when app is in background (e.g. pull something from a server), without APNs
body: <p>Is there a good, Apple-approved alternative to using push notifications to trigger an app to run some code (in particular: pull new messages from a server) in a regular interval?</p>
  
  <ul>
  <li>Disguising as VoIP app is not a good option (won't be approved, see <a href="https://stackoverflow.com/questions/6064747/iphone-repeating-background-task">iPhone: repeating background task</a>)</li>
  <li>I cannot use location updates, it should work if the user does not move around</li>
  </ul>
  
  <p>In the simulator, using <code>beginBackgroundTaskWithExpirationHandler</code> with <code>dispatch_async</code> gives you 10 minutes of background time, and I found out that if the background "restarts itself", the <code>backgroundTimeRemaining</code> property always seems to be reset to 10 minutes. Here's the code.</p>
  
  <pre><code>- (void) work
  {
      UIApplication *application = [UIApplication sharedApplication];
  
      NSLog(@"bg %@ (T-%.1f seconds)",
            [NSDate date],
            [application backgroundTimeRemaining]);
      sleep(10);
  
      [application endBackgroundTask:_bgTask];
      _bgTask = UIBackgroundTaskInvalid;
  
      [self startTask];
  }
  
  - (void)startTask
  {
      UIApplication *application = [UIApplication sharedApplication];
      _bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
          NSLog(@"expired at %@", [NSDate date]);
  
          [application endBackgroundTask:_bgTask];
          _bgTask = UIBackgroundTaskInvalid;
      }];
  
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,
                                               0),
                     ^{ [self work]; });
  }
  
  - (BOOL) application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  {
      /* ... */
  
      [self startTask];
  
      /* ... */
  }
  </code></pre>
  
  <p>Would that be an accepted practice to run something in the background? I mean, most of the time I would just <code>sleep(...)</code> until I want to repeat a network request or do something useful, but the app would never really enter full background mode. Does anyone have experience with this approach? Hint: Only tested on simulator without other running apps.</p>