gpt4 book ai didi

ios - 当应用程序进入后台时,DispatchQueue.asyncAfter 的行为如何?

转载 作者:搜寻专家 更新时间:2023-11-01 06:12:55 34 4
gpt4 key购买 nike

我想知道 DispatchQueue.asyncAfter(deadline:execute:) 在进入后台时的行为。我试图在 documentation 中找到更多信息,但那里什么也没有。

让我们假设我调用的情况:
DispatchQueue.main.asyncAfter(deadline: .now() + 60.0) { ... }

  1. 假设我在 10 秒后进入后台会发生什么。
  2. 它会在后台模式下完成吗?
  3. 如果没有,假设我将在 2 分钟后重新打开应用程序。它会立即调用闭包还是在剩余 50 秒后调用?

对我来说最有趣的部分是了解 计时器 60 秒倒计时何时停止和恢复。

更新

寻找 DispatchQueue.asyncAfter(deadline:execute:)DispatchQueue.asyncAfter(wallDeadline:execute:) 之间的差异我从 Apple Staff ( source ),它实际上回答了这个问题:

By the way, do you know why those two distict types are provided in Swift Dispatch library?

These model the difference between wall time (returned by gettimeofday) and Mach absolute time (returned by mach_absolute_time). The latter is independent of system clock changes but stops when you sleep. In the C API everything is flattened to Mach absolute time, which means you lose critical info. Consider what happens if you schedule a timer for 1 second in the future and then the system sleeps for 2 seconds.

要明确 DispatchQueue.asyncAfter(deadline:execute:) 使用绝对时间而 DispatchQueue.asyncAfter(wallDeadline:execute:) 使用 gettimeofday (wall time) 根据这个。

这是另一个来源:What is the difference between dispatch_time and dispatch_walltime and in what situations is better to use one or the other?

测试

基于此我准备了一个测试来确认它:

override func viewDidLoad() {
super.viewDidLoad()

self.textView.text.append(
"expected times: \n1. \(Date().addingTimeInterval(60.0 * 2))\n" +
"2. \(Date().addingTimeInterval(60.0 * 3))\n" +
"3. \(Date().addingTimeInterval(60.0 * 5))\n\n")

DispatchQueue.main.asyncAfter(deadline: .now() + 60.0 * 2) {
self.textView.text.append("\n\(Date()) fired based on ABSOLUTE time (1)!")
}

DispatchQueue.main.asyncAfter(deadline: .now() + 60.0 * 3) {
self.textView.text.append("\n\(Date()) fired based on ABSOLUTE time (2)")
}

DispatchQueue.main.asyncAfter(deadline: .now() + 60.0 * 5) {
self.textView.text.append("\n\(Date()) fired based on ABSOLUTE time (3)!")
}

DispatchQueue.main.asyncAfter(wallDeadline: .now() + 60.0 * 2) {
self.textView.text.append("\n\(Date()) fired based on WALL time (1)!")
}

DispatchQueue.main.asyncAfter(wallDeadline: .now() + 60.0 * 3) {
self.textView.text.append("\n\(Date()) fired based on WALL time (2)")
}

DispatchQueue.main.asyncAfter(wallDeadline: .now() + 60.0 * 5) {
self.textView.text.append("\n\(Date()) fired based on WALL time (3)!")
}
}

结果

我在带有分离调试器的真实设备上运行它并锁定了手机。 3.5 分钟后,我恢复了应用程序:

fired based on WALL time (1)!
fired based on WALL time (2)!

这两个事件恰好在我恢复应用程序时触发。这证明了上面的说法。后来出现了基于绝对时间的事件,这证实了他们的计时器已经停止。

最佳答案

在前台启动的计时器将在后台运行,如果该应用程序已经出于某些其他原因在后台运行(例如,它正在播放音乐并且打开了音频的后台模式,或者它正在执行后台 Core Location 并打开了 Core Location 的后台模式)。

否则,它将在后台暂停。

关于ios - 当应用程序进入后台时,DispatchQueue.asyncAfter 的行为如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51540559/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com