当应用程序在后台时调度 NSTimer? [英] Scheduled NSTimer when app is in background?

查看:39
本文介绍了当应用程序在后台时调度 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.

使用 AppDelegate 的 applicationDidEnterBackground:applicationWillEnterForeground: 方法来获得您想要的行为.它更健壮,因为当您的应用程序因重启或内存压力而完全终止时,它也能正常工作.

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天全站免登陆