Swift - GCD timer使用

作者: GA_ | 来源:发表于2018-07-20 11:57 被阅读12次
private var timer: DispatchSourceTimer?
    
    func addTimer() {
         // 子线程创建timer
        timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.global())
        //        let timer = DispatchSource.makeTimerSource()
        /*
         dealine: 开始执行时间
         repeating: 重复时间间隔
         leeway: 时间精度
         */
        timer?.schedule(deadline: .now() + .seconds(5), repeating: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.seconds(0))
        // timer 添加事件
        timer?.setEventHandler {
            print("timer事件")
        }
        timer?.resume()
    }
    // timer暂停
    func stopTimer() {
        timer?.suspend()
    }
    // timer结束
    func cancleTimer() {
        guard let t = timer else {
            return
        }
        t.cancel()
        timer = nil
    }

timer:https://github.com/100mango/SwiftTimer
定时器:https://github.com/dalu93/Each

相关文章

网友评论

    本文标题:Swift - GCD timer使用

    本文链接:https://www.haomeiwen.com/subject/ccbfmftx.html