您可以定义GCD计时器属性(因为与NSTimer
/ 不同Timer
,您必须维护自己对GCD计时器的强引用):
var timer: DispatchSourceTimer!
Run Code Online (Sandbox Code Playgroud)
然后使用以下方法制作一个计时器(可能是.strict
一个无需进行合并,应用程序午睡等操作的计时器,并且要意识到所涉及的电源/电池/等方面的隐患)makeTimerSource(flags:queue:)
:
let queue = DispatchQueue(label: "com.domain.app.timer", qos: .userInteractive)
timer = DispatchSource.makeTimerSource(flags: .strict, queue: queue)
timer.scheduleRepeating(deadline: .now(), interval: 0.0001, leeway: .nanoseconds(0))
timer.setEventHandler {
// do something
}
timer.resume()
Run Code Online (Sandbox Code Playgroud)
注意,您应该适当地处理计时器无法满足您所寻找精度的情况。如文档所述:
请注意,即使将回程值指定为零,所有计时器也会有一些等待时间。
归档时间: |
|
查看次数: |
1335 次 |
最近记录: |