OGeek|极客世界-中国程序员成长平台

标题: ios - 为什么计时器有时会这么快地调用它的 block [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:59
标题: ios - 为什么计时器有时会这么快地调用它的 block

我创建一个计时器并每 5 秒调用一次它的 block 。然后我申请进入后台并在一段时间后进入前台。但它有时可以快速调用 block 。

let _ = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { (timer) in
        print("--------")
   }

当我进入前台时,第一次打印和第二次打印的间隔有时可能不到一秒。这种情况下时间间隔无效吗?



Best Answer-推荐答案


要了解该行为,您需要了解 NSTimerRunLoop 的工作原理。简单来说,RunLoop 会检查 Timer 是否应该触发,如果是,它会通知 Timer 触发选择器,否则不会。现在,由于您在后台,您的 RunLoop 不会检查事件,因此它无法通知 Timer。但是一旦它进入前台,它会看到它需要通知 Timer,即使它超过了 fireDate。

时间线图:

设 A(第 5 秒)和 B(第 10 秒)为计时器触发事件​​。计划在计时器上 Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true)

C 进入后台(0 秒)

D 会回到前台(第 9 秒,在 A 和 B 之间)。

-----> A ------> B

C--------->D

解释:

在 C 上,RunLoop 将暂停。因此,在 RunLoop 恢复处理之前无法处理事件 A,这在事件 D 上。在事件 D 上,它将看到事件 A 应该触发,因此它会通知计时器。一秒钟后,RunLoop 会看到 Event B 已经发生,因此它会再次通知 Timer。这个场景解释了为什么你的事件在一秒钟的时间间隔内打印出来。只是延迟的事件处理使它看起来更早触发,而实际上它被延迟处理。

苹果文档:

A timer is not a real-time mechanism. If a timer’s firing time occurs during a long run loop callout or while the run loop is in a mode that isn't monitoring the timer, the timer doesn't fire until the next time the run loop checks the timer. Therefore, the actual time at which a timer fires can be significantly later.

资源:What is an NSTimer's behavior when the app is backgrounded? , NSRunLoop 和 Timer 文档

建议:

应用程序进入后台后停止计时器,但存储 fireDate。回到前台后,检查 fireDate 是否超过 Date()。然后创建一个新的 Timer 来在前台处理事件。

关于ios - 为什么计时器有时会这么快地调用它的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53624323/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4