程序员iOS开发进阶iOS学习笔记

Swift - GCD timer使用

2018-07-20  本文已影响12人  GA_
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

上一篇 下一篇

猜你喜欢

热点阅读