简体   繁体   English

延迟后在iOS上执行后台任务

[英]Perform a background task on iOS after delay

Is it possible to run a background task with a delay of about 5 minutes, with the ability to cancel it if the app comes into foreground before the task is executed? 如果后台应用程序在执行任务之前进入前台,则可以延迟大约5分钟来运行后台任务吗?

To explain the context of this, the app I am working on has a fairly lengthy set up time when it's opening up. 为了解释这种情况,我正在开发的应用在打开时具有相当长的设置时间。 Ideally it needs to clean up all the resources when going into background, and recreate them from scratch when coming into foreground. 理想情况下,它需要在进入后台时清理所有资源,并在进入前台时从头开始重新创建它们。 This is partly for security, partly to reduce device energy use (network, BLE). 这部分是为了安全,部分是为了减少设备能耗(网络,BLE)。

This creates an awkward user experience if the user switches to another app for a brief time and comes back to mine. 如果用户在短时间内切换到另一个应用程序并回到我的应用程序,则会带来尴尬的用户体验。 They are stuck waiting for a few seconds for everything to reinitialize. 他们被困了几秒钟,等待一切重新初始化。

As a compromise, I want to add a delay to the clean up procedure, say 5 minutes. 作为一种折衷,我想在清理过程中增加一个延迟,例如5分钟。 So that if the user comes back in less than 5 minutes, everything is still there, available immediately. 这样,如果用户在不到5分钟的时间内回来,则一切仍然存在,可以立即使用。 Otherwise it does take a bit of time to reinitialize. 否则,它会花费一些时间来重新初始化。 How could I implement it? 我该如何实施?

In iOS, an app can have up to 3 minutes of background processing time when a user exists the app. 在iOS中,当用户存在该应用时,该应用最多可以有3分钟的后台处理时间。 So if you are willing to use a 3 minute timer, you could use beginBackgroundTaskWithExpirationHandler: on UIApplication.sharedApplication . 因此,如果您愿意使用3分钟的计时器,则可以在UIApplication.sharedApplication上使用beginBackgroundTaskWithExpirationHandler: The background task could then use dispatch_after with a time of 2 minutes, 55 seconds or something close to 3 minutes and do the cleanup. 然后,后台任务可以使用2分钟,55秒或接近3分钟的时间使用dispatch_after进行清理。 When the user comes back in the app, if the time hasn't expired, you could set a flag or reset the timer so that the dispatch_after does nothing. 当用户返回应用程序时,如果时间尚未到期,则可以设置标志或重置计时器,以便dispatch_after不执行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM