Timer in background

As we know, there are some restrictions for applications running in the background. For example, NSTimer does not work. I tried to write a "Timer" like this, which might work in the background.

-(UIBackgroundTaskIdentifier)startTimerWithInterval:(NSTimeInterval)interval run:(void (^)())runBlock complete:(void (^)())completeBlock
{
    NSTimeInterval delay_in_seconds = interval;
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, delay_in_seconds * NSEC_PER_SEC);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    // ensure the app stays awake long enough to complete the task when switching apps
    UIBackgroundTaskIdentifier taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{

        completeBlock();

    }];

    NSLog(@"remain task time = %f,taskId = %d",[UIApplication sharedApplication].backgroundTimeRemaining,taskIdentifier);

    dispatch_after(delay, queue, ^{
        // perform your background tasks here. It a block, so variables available in the calling method can be referenced here.
        runBlock();

        // now dispatch a new block on the main thread, to update our UI
        dispatch_async(dispatch_get_main_queue(), ^{

            completeBlock();
            [[UIApplication sharedApplication] endBackgroundTask:taskIdentifier];
        });
    });

    return taskIdentifier;

}

I called this function as follows:

-(void)fire
{
    self.taskIdentifier = [self startTimerWithInterval:10
                                                   run:^{
                                                           NSLog(@"timer!");
                                                           [self fire];
                                                   }
                                              complete:^{

                                                  NSLog(@"Finished");

                                              }];

}

This timer works fine except for one problem. The longest period for a background task is 10 minutes. (Refer to NSLog at startTimerWithInterval).

If any way to get my timer to work for more than 10 minutes? By the way, my application is a BLE application, I already installed UIBackgroundModes in bluetooth-central.

+1
source share

All Articles