swift多线程定时器的使用
func countDown(_ timeOut:Int,view: UIView){
var timeout = timeOut
let queue:DispatchQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default)
if timer == nil {
timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: 0), queue: queue) /*Migrator FIXME: Use DispatchSourceTimer to avoid the cast*/ as? DispatchSource
}
timer.schedule(deadline: DispatchTime.now(), repeating: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.seconds(0))
// timer.setTimer(start: DispatchWallTime(time: nil), interval: 1*NSEC_PER_SEC, leeway: 0)
//每秒执行
timer.setEventHandler(handler: { () -> Void in
if (timeout<=0) { //倒计时结束,关闭
self.timer.cancel()
DispatchQueue.main.async(execute: { () -> Void in
//设置界面的按钮显示 根据自己需求设置
//print("倒计时")
view.removerAlertView()
})
}else {//正在倒计时
let seconds = timeout % 60
// let strTime = NSString.localizedStringWithFormat("%.2d", seconds)
DispatchQueue.main.async(execute: { () -> Void in
//设置界面的按钮显示 根据自己需求设置
self.timerLabel.text = "(seconds)"
})
timeout -= 1;
}
})
timer.resume()
}
暂停
var isSuspend = false
@objc func tap(_ gesture: UITapGestureRecognizer) {
if timer != nil && timer.isCancelled == false {
if isSuspend {
timer.resume()
} else {
timer.suspend()
}
isSuspend = !isSuspend
}
}
销毁
deinit {
if isSuspend {
timer?.resume() //先继续运行再销毁
}
timer?.cancel()
timer = nil
}