调度源计时器时间表超时



使用以下Swift代码,我试图创建一个每小时运行一次的任务:

let queue: DispatchQueue = .main
let timer = DispatchSource.makeTimerSource(queue: queue)
timer.schedule(deadline: .now(), repeating: .seconds(3600), leeway: .milliseconds(100)
timer.setEventHandler { [weak self] in
// run code
}

现在,当我将重复设置为较低的数字时,比如10秒或事件150秒,它在前景和背景中都会按预期触发(或者,更确切地说,一旦前景命中,如果计时器在背景中熄灭,它就会触发(。然而,当我让应用程序超时到锁定屏幕,等待一个小时时,它不会显示。

苹果对DispatchSource时间表是否有一些超时?如果是,那是什么?有什么办法可以改变或绕过它吗?

编辑

当它后台时,我不想要特殊的功能,我希望代码保持正常运行,并在超时发生时触发事件处理程序,即使它在后台中

我最终采纳了matt的建议,并在每次调用代码时节省了时间,如下所示。工作得很好!

let timeOfLastCheck = Date()
let queue: DispatchQueue = .main
let timer = DispatchSource.makeTimerSource(queue: queue)
timer.schedule(deadline: .now(), repeating: .seconds(3600), leeway: .milliseconds(100)
timer.setEventHandler { [weak self] in
timeOfLastCheck = Date()
// run code
}

在其他地方,计时器实际上是在哪里创建的:

let notificationCenter: NotificationCenter = .default
let activeNotificationToken = notificationCenter.addObserver(
forName: UIApplication.didBecomeActiveNotification,
object: nil,
queue: nil
) { [weak self] _ in
let now = Date()
if let `self` = self,
let timeInterval = TimeInterval(dispatchTimeInterval: self.interval), // TimeInterval is extended elsewhere to be able to take in a DispatchTimeInterval in the init
now > timeOfLastCheck.addingTimeInterval(timeInterval) {
self.timeOfLastCheck = Date()
// run code
}
}

最新更新