调用一个延迟为15秒的方法,而不考虑应用状态



我需要在每15秒内调用一个方法,无论任何事实,无论是在foreground的任何视图控制器上,无论是在background还是killed,我都需要随时调用它。

我知道我可以使用NSTimer执行延迟任务

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

但是,我想知道在哪里实现它,以便它可以满足我的条件。我想我可以在App Delegate中使用它,但我需要一个指导来正确实现它。

在App Delegate类中调用它是正确的,但在以下情况下它将不起作用。

  • 如果你的应用程序被后台杀死,它将无法工作。
  • 它不会一直处于后台模式。操作系统将在一段时间后停止该进程。

-如果应用程序被杀死,你不能做任何事情。

-当应用程序在后台运行时,操作系统可能会在一段时间间隔后杀死该进程(我认为是15秒)。

虽然你可以注册位置的变化,而应用程序是在后台。在这种情况下,你的应用程序将继续接收位置更新(如谷歌地图)。

-(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];
        });
    }
}
     [NSThread sleepForTimeInterval:4.0f];
     dispatch_async(dispatch_get_main_queue(),
                    ^{
               //write you code if you want fire any method after 4 sec//          
                    }
                    );

最新更新