无论应用程序状态如何,调用延迟 15 秒的方法 [英] Call a method with delay of 15 sec irrespective of app state

查看:45
本文介绍了无论应用程序状态如何,调用延迟 15 秒的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要每 15 秒调用一次方法,不管它是否在 foreground 中的任何视图控制器上,无论它在 background 中还是在killed,我需要随时调用它.

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.

我知道我可以使用 NSTimer

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

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

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.

推荐答案

-如果应用程序被杀死,您将无能为力.

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

-当应用程序在后台时,操作系统可能会在一定时间间隔(我相信是 15 秒)后终止该进程.

-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];

        });
    }

}

这篇关于无论应用程序状态如何,调用延迟 15 秒的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆