ios - Swift 3 精确定时器重复(iOS 9)

标签 ios swift timer ios9 nstimer

我有一个精确的计时器,需要每 40 毫秒更新一次(尽可能精确)。在iOS10上它很好(我使用新的scheduleRepeating方法),但在iOS9上我需要使用旧的方式(scheduledTimer code>)而且它相当滞后(有时 24ms,有时 72...),所以我的硬件界面和视觉效果也很滞后。

有什么建议吗?

func launchTimer() {
    if #available(iOS 10.0, *) {
            startTickTimer()
    } else {
        let timerQueue =  DispatchQueue(label: "my.queue.tickTimer", attributes: .concurrent)
        self.swiftTimer = Timer.scheduledTimer(timeInterval: period, target: self, selector: #selector(executeTimer), userInfo: nil, repeats: true)
        timerQueue.async {
            RunLoop.current.add(self.swiftTimer!, forMode: RunLoopMode.defaultRunLoopMode)
        }
    }
}

static func startTickTimer() {
    let queue = DispatchQueue(label: "my.queue.tickTimer", attributes: .concurrent)
    DMXTimer.tickTimer?.cancel()
    DMXTimer.tickTimer = DispatchSource.makeTimerSource(queue: queue)
    DMXTimer.tickTimer?.scheduleRepeating(deadline: .now(), interval: .milliseconds(40), leeway: .seconds(1))
    DMXTimer.tickTimer?.setEventHandler {
        executeTimer()
    }
    DMXTimer.tickTimer?.resume()
}

static func executeTimer() {
    print("hello moto")
}

最佳答案

来自关于 NSTimer 的 Apple 文档:

A timer is not a real-time mechanism. If a timer’s firing time occurs during a long run loop callout or while the run loop is in a mode that isn't monitoring the timer, the timer doesn't fire until the next time the run loop checks the timer. Therefore, the actual time at which a timer fires can be significantly later. See also Timer Tolerance.

如果你想要一个非常精确的计时器,你可以检查 Apple Tech Note 的实现。并在 Swift 中进行调整或使用 CADisplayLink 进行显示更新。

关于ios - Swift 3 精确定时器重复(iOS 9),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44066584/

相关文章:

iOS 14 链接模块标志 'Dwarf Version' : IDs have conflicting behaviors

swift - 如何在 swift 中使用谓词?

java - 如何在 (mm :ss) format using editText?

android - 使用计时器进行 wifi 扫描 android 的意外结果

iOS 在应用程序启动期间检测到 Airplay

ios - 使用 stringByReplacingOccurrencesOfString 来考虑 "words"

iphone - 当电话或其他事件关闭音乐播放器 iPhone 时捕捉事件

swift - 使用 CreateML 在 Swift 中为机器学习创建数据表

swift - 如何在 Alamofire 中使用(+ 加号)发布参数

ios - 如何使 ScrollView 在到达最后一张图像后从第一页开始滚动?