[英]How to pause/resume a DispatchWorkItem in Swift
我有这个对象:
lockWallTask = DispatchWorkItem(block: {
self.lockWall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10, execute: lockWallTask)
因此它在10秒后执行。 但是,我试图暂停此项目,然后恢复它。 例如:
我会在3秒钟后暂停该项目,这意味着还有7秒钟的执行时间。 我做了5分钟的其他工作,然后我继续执行该项目,但还有7秒可以执行。 我正在努力实现这一目标:
DispatchQueue.resume(task)
DispatchQueue.suspend(task)
但是,给我这个编译错误:
我不明白那个错误。 可变任务的类型为“ DispatchWorkItem”
我如何实现暂停或挂起DispatchWorkItem,然后恢复它?
您需要使用DispatchSource
计时器,您可以在其中暂停,继续和停止并相应地执行操作。
var timer: DispatchSource?
func resumeTimer() {
guard let timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: 0), queue: mainQueue) as? DispatchSource else { return }
timer.setEventHandler {
mainQueue.async(execute: { [weak self] in
self?.runTimer()
})
}
timer.scheduleRepeating(deadline: .now(), interval: .seconds(10), leeway: .seconds(1))
timer.resume()
}
func pausedTimer() {
if let timer = timer {
timer.suspend()
}
}
func stoppedTimer() {
if let timer = timer {
timer.cancel()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.