DispatchSourceTimer
优质
小牛编辑
136浏览
2023-12-01
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()
}