Swift 3 - 如何让计时器在后台运行

时间:2022-07-29 02:46:38

i am trying to do an application which can make a timer run in background.

我正在尝试做一个可以使计时器在后台运行的应用程序。

here's my code:

这是我的代码:

let taskManager = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.scheduleNotification), userInfo: nil, repeats: true)
        RunLoop.main.add(taskManager, forMode: RunLoopMode.commonModes)

above code will perform a function that will invoke a local notification. this works when the app is in foreground, how can i make it work in the background?

上面的代码将执行一个将调用本地通知的函数。当应用程序处于前台时,这是有效的,我如何让它在后台运行?

i tried to put several print lines and i saw that when i minimize (pressed the home button) the app, the timer stops, when i go back to the app, it resumes.

我试图放几条打印线,我看到当我最小化(按下主页按钮)应用程序时,计时器停止,当我回到应用程序时,它恢复。

i wanted the timer to still run in the background. is there a way to do it?

我希望计时器仍然在后台运行。有办法吗?

here's what i want to happen:

这就是我想要发生的事情:

run app -> wait 10 secs -> notification received -> wait 10 secs -> notification received -> and back to wait and received again

运行应用程序 - >等待10秒 - >收到通知 - >等待10秒 - >收到通知 - >然后返回等待再次收到

that happens when in foreground. but not in background. pls help.

在前景时发生。但不是在后台。请帮助。

5 个解决方案

#1


5  

A timer can run in the background only if both the following are true:

只有满足以下两个条件时,计时器才能在后台运行:

  • Your app for some other reason runs in the background. (Most apps don't; most apps are suspended when they go into the background.) And:

    您的应用程序由于其他原因在后台运行。 (大多数应用程序没有;大多数应用程序在进入后台时都会被暂停。)并且:

  • The timer was running already when the app went into the background.

    当应用程序进入后台时,计时器已经运行。

#2


4  

you can go to Capabilities and turn on background mode and active Audio. AirPlay, and picture and picture.

您可以转到功能并打开后台模式和活动音频。 AirPlay,图片和图片。

It really works . you don't need to set DispatchQueue . you can use of Timer.

真的行 。你不需要设置DispatchQueue。你可以使用Timer。

        Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (t) in

           print("time")
        }

#3


0  

Timer won't work in background. For background task you can check this link below...

定时器无法在后台运行。对于后台任务,您可以查看以下链接...

https://www.raywenderlich.com/143128/background-modes-tutorial-getting-started

#4


-1  

create Global uibackground task identifier.

创建全局uibackground任务标识符。

UIBackgroundTaskIdentifier bgRideTimerTask;

now create your timer and add BGTaskIdentifier With it, Dont forget to remove old BGTaskIdentifier while creating new Timer Object.

现在创建你的计时器并添加BGTaskIdentifier用它,不要忘记在创建新的Timer对象时删除旧的BGTaskIdentifier。

 [timerForRideTime invalidate];
 timerForRideTime = nil;

 bgRideTimerTask = UIBackgroundTaskInvalid;

 UIApplication *sharedApp = [UIApplication sharedApplication];       
 bgRideTimerTask = [sharedApp beginBackgroundTaskWithExpirationHandler:^{

                            }];
 timerForRideTime =  [NSTimer scheduledTimerWithTimeInterval:1.0
                                                                                 target:self
                                                                               selector:@selector(timerTicked:)
                                                                               userInfo:nil
                                                                                repeats:YES]; 
                                                   [[NSRunLoop currentRunLoop]addTimer:timerForRideTime forMode: UITrackingRunLoopMode];

Here this will work for me even when app goes in background.ask me if you found new problems.

即使应用程序进入后台,这对我也有用。如果你发现了新的问题,请告诉我。

#5


-2  

As others pointed out, Timer cannot make a method run in Background. What you can do instead is use while loop inside async task

正如其他人所指出的,Timer无法在Background中运行方法。你可以做的是在async任务中使用while循环

DispatchQueue.global(qos: .background).async {
                while (shouldCallMethod) {
                    self.callMethod()
                    sleep(1)
                }
}

#1


5  

A timer can run in the background only if both the following are true:

只有满足以下两个条件时,计时器才能在后台运行:

  • Your app for some other reason runs in the background. (Most apps don't; most apps are suspended when they go into the background.) And:

    您的应用程序由于其他原因在后台运行。 (大多数应用程序没有;大多数应用程序在进入后台时都会被暂停。)并且:

  • The timer was running already when the app went into the background.

    当应用程序进入后台时,计时器已经运行。

#2


4  

you can go to Capabilities and turn on background mode and active Audio. AirPlay, and picture and picture.

您可以转到功能并打开后台模式和活动音频。 AirPlay,图片和图片。

It really works . you don't need to set DispatchQueue . you can use of Timer.

真的行 。你不需要设置DispatchQueue。你可以使用Timer。

        Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (t) in

           print("time")
        }

#3


0  

Timer won't work in background. For background task you can check this link below...

定时器无法在后台运行。对于后台任务,您可以查看以下链接...

https://www.raywenderlich.com/143128/background-modes-tutorial-getting-started

#4


-1  

create Global uibackground task identifier.

创建全局uibackground任务标识符。

UIBackgroundTaskIdentifier bgRideTimerTask;

now create your timer and add BGTaskIdentifier With it, Dont forget to remove old BGTaskIdentifier while creating new Timer Object.

现在创建你的计时器并添加BGTaskIdentifier用它,不要忘记在创建新的Timer对象时删除旧的BGTaskIdentifier。

 [timerForRideTime invalidate];
 timerForRideTime = nil;

 bgRideTimerTask = UIBackgroundTaskInvalid;

 UIApplication *sharedApp = [UIApplication sharedApplication];       
 bgRideTimerTask = [sharedApp beginBackgroundTaskWithExpirationHandler:^{

                            }];
 timerForRideTime =  [NSTimer scheduledTimerWithTimeInterval:1.0
                                                                                 target:self
                                                                               selector:@selector(timerTicked:)
                                                                               userInfo:nil
                                                                                repeats:YES]; 
                                                   [[NSRunLoop currentRunLoop]addTimer:timerForRideTime forMode: UITrackingRunLoopMode];

Here this will work for me even when app goes in background.ask me if you found new problems.

即使应用程序进入后台,这对我也有用。如果你发现了新的问题,请告诉我。

#5


-2  

As others pointed out, Timer cannot make a method run in Background. What you can do instead is use while loop inside async task

正如其他人所指出的,Timer无法在Background中运行方法。你可以做的是在async任务中使用while循环

DispatchQueue.global(qos: .background).async {
                while (shouldCallMethod) {
                    self.callMethod()
                    sleep(1)
                }
}