0

I am trying to make an application that executes a function every two seconds. To accomplish that, I use Timer.scheduledTimer function. The problem is that the function is not executed every two seconds as it should. Usually the interval at the beginning of the application is 2 seconds, but later (after like half a minute) the interval is sometimes 7 seconds, sometimes 13 etc.

Here is my code:

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.
        }
    }

}

So what the function of the application is, it prints the time every two seconds. This is the output I'm getting (you see that the function does not execute every two seconds on each interval):

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

I am a beginner in Swift language, can someone please point me in the right direction? I also tried doing it without the Timer, but just using a function with a infinite loop (while(true)) and sleeping for two seconds inside that loop after time has been printed.

I am running Swift version 5.0.1, if that matters.

Thanks!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
MrWhite
  • 179
  • 3
  • 11

1 Answers1

0

App Nap was the reason for this: Swift timer is not executing on precise time

Here is how I fixed it/disabled App Nap for my application: Disable app nap in Swift

MrWhite
  • 179
  • 3
  • 11