Using Timer on Linux?

I'm trying to use Timer in my SDL-based app on Linux. It works on macOS, but for some reason when my timer is about to fire execution of my app stops.

I call dispatchMain after setting up my app. I created the timer like this:

self.oneSecondUpdate = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true)
{ inTimer in
	debugLog("one second update")
	self.updateDisplay()
}

It seems my SDL event loop runs for about one second before hanging. The timer body is never called.

Any ideas? Thanks.

This small sample works for me on a Pi:

import Foundation

let runloop = RunLoop.current
var shouldKeepRunning = true

let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false, block: {(theTimer) in
    print("timer fired")
})


while shouldKeepRunning == true &&
runloop.run(mode: RunLoop.Mode.default, before: Date.distantFuture) {}
1 Like

And this fails on my Mac:

import Foundation

func main() {
    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { inTimer in
        print("one second update")
    }
    dispatchMain()
}

main()

(-:

Foundation timers require you to run the run loop. dispatchMain does not do this. If you use Foundation timers, you have to use RunLoop. If you don’t want to do that, use Dispatch timers.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

1 Like

Oh, good to know. Any chance these things will be consolidated at some point in the future?

Ah, I wasn't running the run loop.

Terms of Service

Privacy Policy

Cookie Policy