gpt4 book ai didi

swift - DispatchSourceTimer 和 Swift 3.0

转载 作者:行者123 更新时间:2023-11-30 12:44:16 24 4
gpt4 key购买 nike

我不知道如何让调度计时器在 Swift 3.0 中重复工作。我的代码:

let queue = DispatchQueue(label: "com.firm.app.timer",
attributes: DispatchQueue.Attributes.concurrent)
let timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: UInt(0)),
queue: queue)

timer.scheduleRepeating(deadline: DispatchTime.now(),
interval: .seconds(5),
leeway: .seconds(1)
)

timer.setEventHandler(handler: {
//a bunch of code here
})

timer.resume()

计时器只触发一次,并且不会像应有的那样重复自身。我该如何解决这个问题?

最佳答案

确保计时器不会超出范围。与Timer(您安排它的RunLoop)不同,您需要维护自己的强引用,直到Timer无效为止。引用您的 GCD 计时器,例如:

private var timer: DispatchSourceTimer?

private func startTimer() {
let queue = DispatchQueue(label: "com.firm.app.timer", attributes: .concurrent)

timer = DispatchSource.makeTimerSource(queue: queue)

timer?.setEventHandler { [weak self] in // `[weak self]` only needed if you reference `self` in this closure and you want to prevent strong reference cycle
print(Date())
}

timer?.schedule(deadline: .now(), repeating: .seconds(5), leeway: .milliseconds(100))

timer?.resume()
}

private func stopTimer() {
timer = nil
}

关于swift - DispatchSourceTimer 和 Swift 3.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41842933/

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