Swift 5.x DispatchSourceTimer

swift下使用timer防止crash

  • 定义:
// Timer Suspend 状态记录
private var isSusspended: Bool = true
private lazy var autoLearnTimer: DispatchSourceTimer? = {
        let timer: DispatchSourceTimer = DispatchSource.makeTimerSource(flags: .strict, queue: DispatchQueue.global())
        timer.schedule(deadline: .now(), repeating: requestTimeInterVal)
        timer.setEventHandler { [weak self] in
            self?.loop()
        }
        return timer
    }()
  • 开始、暂停和销毁
// MARK: timer 接口
extension ViewController {
    private func startTimer() {
        if isSusspended {
            self.autoLearnTimer?.resume()
        }
        isSusspended = false
    }

    private func stopTimer() {
        if isSusspended {
            return
        }
        isSusspended = true
        DispatchQueue.main.async {
            self.autoLearnTimer?.suspend()
        }
        print("停止定时器")
    }
    private func releaseTimer() {
        if isSusspended {
            self.autoLearnTimer?.resume()
        }
        self.autoLearnTimer?.cancel()
    }
}
deinit {
        releaseTimer()
    }

你可能感兴趣的:(Swift 5.x DispatchSourceTimer)