DispatchSourceTimer 和 Swift 3.0 [英] DispatchSourceTimer and Swift 3.0

查看:29
本文介绍了DispatchSourceTimer 和 Swift 3.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can't figure out how to make dispatch timer work repeatedly in Swift 3.0. My code:

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 just fires one time and doesn't repeat itself like it should be. How can I fix this?

推荐答案

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

Make sure the timer doesn't fall out of scope. Unlike Timer (where the RunLoop on which you schedule it keeps the strong reference until the Timer is invalidated), you need to maintain your own strong reference to your GCD timers, e.g.:

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
}

这篇关于DispatchSourceTimer 和 Swift 3.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆