【问题标题】:Swift scheduledTimer lag?Swift scheduleTimer 滞后?
【发布时间】:2019-10-01 20:14:09
【问题描述】:

我正在尝试制作一个每两秒执行一次功能的应用程序。为此,我使用 Timer.scheduledTimer 函数。 问题是该函数没有按应有的每两秒执行一次。通常应用程序开始时的间隔是 2 秒,但后来(大约半分钟后)间隔有时是 7 秒,有时是 13 秒等。

这是我的代码:

import Cocoa

class ViewController: NSViewController {

    @objc func glavno(){

      let date = Date()
      var calendar = Calendar.current
      calendar.timeZone = TimeZone(identifier: "UTC")!              
      let components = calendar.dateComponents([.hour, .year, .minute], from: date)
      let hour = calendar.component(.hour, from: date)
      let minutes = calendar.component(.minute, from: date)
      let seconds = calendar.component(.second, from: date)
      print("\(hour):\(minutes):\(seconds)")

    }

    var timer = Timer()

    override func viewDidLoad() {

        //Load UI
        super.viewDidLoad()

        //Start the task
        timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.glavno), userInfo: nil, repeats: true)  

    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

}

那么应用程序的功能是什么,它每两秒打印一次时间。 这是我得到的输出(您会看到该函数不会在每个时间间隔每两秒执行一次):

20:9:21
20:9:23
20:9:25
20:9:37
20:9:49
20:10:1
20:10:3
20:10:5
20:10:17
20:10:23

我是 Swift 语言的初学者,有人可以指点我正确的方向吗?我也尝试过不使用 Timer,但只使用具有无限循环的函数 (while(true)) 并在打印时间后在该循环内休眠两秒钟。

我正在运行 Swift 版本 5.0.1,如果这很重要的话。

谢谢!

【问题讨论】:

    标签: swift cocoa timer


    【解决方案1】:

    App Nap 是这个原因:Swift timer is not executing on precise time

    这是我为我的应用程序修复/禁用 App Nap 的方法:Disable app nap in Swift

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-29
      • 2018-12-26
      相关资源
      最近更新 更多