DispatchSourceTimer and Swift 3.0

夙愿已清 提交于 2019-11-27 19:06:00

Make sure the timer doesn't fall out of scope. Unlike NSTimer, you need to maintain a strong reference to your GCD timers, e.g.:

var timer: DispatchSourceTimer?

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

    timer?.cancel()        // cancel previous timer if any

    timer = DispatchSource.makeTimerSource(queue: queue)

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

    // or, in Swift 3:
    //
    // timer?.scheduleRepeating(deadline: .now(), interval: .seconds(5), leeway: .seconds(1))

    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?.resume()
}

private func stopTimer() {
    timer?.cancel()
    timer = nil
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!