应用程序在后台时预定的NSTimer? [英] Scheduled NSTimer when app is in background?

查看:92
本文介绍了应用程序在后台时预定的NSTimer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当应用在后台时,人们如何处理预定的NSTimer?

How do people deal with a scheduled NSTimer when an app is in the background?

假设我每小时都在我的应用中更新一些内容。

Let's say I update something in my app every hour.

updateTimer = [NSTimer scheduledTimerWithTimeInterval:60.0*60.0 
target:self 
selector:@selector(updateStuff) 
userInfo:nil 
repeats:YES];

在后台,此计时器显然不会触发(?)。当用户回到应用程序时应该怎么办?计时器是否仍然在运行,但时间相同?

When in the background, this timer obviously doesn't fire(?). What should happen when the user comes back to the app..? Is the timer still running, with the same times?

如果用户在一小时内回来会怎么样?它是否会在错过的所有时间触发,还是会等到下一个更新时间?

And what would would happen if the user comes back in over an hour. Will it trigger for all the times that it missed, or will it wait till the next update time?

我希望它做的是在应用程序到来后立即更新进入前景,如果它应该被解雇的日期是过去。这可能吗?

What I would like it to do is update immediately after the app comes into the foreground, if the date it should have fired is in the past. Is that possible?

推荐答案

你不应该通过设置一个计时器来解决这个问题,因为你不能执行任何代码在后台。想象一下,如果用户在此期间或其他边缘情况下重启iPhone,将会发生什么。

You shouldn't solve this problem by setting a timer, because you're not allowed to execute any code in the background. Imagine what will happen if the user restarts his iPhone in the meantime or with some other edge cases.

使用 applicationDidEnterBackground: applicationWillEnterForeground: AppDelegate的方法可以获得所需的行为。它的功能更强大,因为当你的应用程序因重启或内存压力而被完全杀死时它也会起作用。

Use the applicationDidEnterBackground: and applicationWillEnterForeground: methods of your AppDelegate to get the behavior you want. It's way more robust, because it will also work when your App is completely killed because of a reboot or memory pressure.

你可以节省计时器下次启动的时间。你的应用程序将进入后台并检查当应用程序返回前台时是否应该采取措施。也可以在此方法中停止并启动计时器。在您的应用程序运行时,您可以使用计时器在适当的时刻触发更新。

You can save the time the timer will fire next when your App is going to the background and check if you should take action when the App comes back to the foreground. Also stop and start the timer in this methods. While your App is running you could use a timer to trigger the update at the right moment.

这篇关于应用程序在后台时预定的NSTimer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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