Swift | GCD定时器倒计时

var timeObserve: DispatchSourceTimer! //定时任务
//MARK:  GCD定时器倒计时
    ///
    /// - Parameters:
    ///   - timeInterval: 间隔时间
    ///   - repeatCount: 重复次数
    ///   - handler: 循环事件,闭包参数: 1.timer 2.剩余执行次数
    func dispatchTimer(timeInterval: Double, repeatCount: Int, handler: @escaping (DispatchSourceTimer?, Int) -> Void) {
        
        if repeatCount <= 0 {
            return
        }
        if timeObserve != nil {
            timeObserve.cancel()//销毁旧的
        }
        // 初始化DispatchSourceTimer前先销毁旧的,否则会存在多个倒计时
        let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        timeObserve = timer
        var count = repeatCount
        timer.schedule(deadline: .now(), repeating: timeInterval)
        timer.setEventHandler {
            count -= 1
            DispatchQueue.main.async {
                handler(timer, count)
            }
            if count == 0 {
                timer.cancel()
            }
        }
        timer.resume()
        
    }

你可能感兴趣的:(Swift | GCD定时器倒计时)