小编典典

DispatchSourceTimer和Swift 3.0

swift

我不知道如何使调度计时器在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()

计时器只会触发一次,不会像应有的那样重复自身。我怎样才能解决这个问题?


阅读 368

收藏
2020-07-07

共1个答案

小编典典

确保计时器不超出范围。与TimerRunLoop在其计划表上保留强引用直到Timer无效)不同,您需要维护自己对GCD计时器的强引用,例如:

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
}
2020-07-07