Call a method with delay of 15 sec irrespective of

2019-05-21 19:43发布

问题:

I need to call a method in every 15 seconds irrespective of any fact, whether it is on any view controller in foreground, whether it is in background or it is killed, I need to call it at all times.

I know I can do the delay task using NSTimer

NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval: 15.0 target: self
                               selector: @selector(callAfterFifteenSeconds:) userInfo: nil repeats: YES];

But, I wanted to know where to implement it so that it could fulfil my condition. I guess I can use it in App Delegate but I need a guidance for this to implement it correctly.

回答1:

Calling it in App Delegate class is right place but it will not work for following cases.

  • It will not work if your app is killed from back ground.
  • It will not in background mode continuously. OS will stop that process after certain period of time.


回答2:

-If the app is killed, you cannot do anything.

-When the app is in background, the OS may kill that process after certain time interval (I believe it is 15 seconds).

Though you can register for location changes, while the app is in background. In that case, your app will continue to receive location updates (such as for google maps).

-(void)callAfterFifteenSeconds {

    //1.) do your work


    //2.) If required, you can also choose to skip the next scheduling.
    BOOL shouldSchedule = YES;

    if (shouldSchedule) {
        //3.)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //
            [self callAfterFifteenSeconds];

        });
    }

}


回答3:

     [NSThread sleepForTimeInterval:4.0f];
     dispatch_async(dispatch_get_main_queue(),
                    ^{
               //write you code if you want fire any method after 4 sec//          

                    }
                    );