Hello,
please let me know if I'm holding it wrong, but I've got an odd behaviour in Timer that is different on Linux compared to macOS.
Basically if I create a non-scheduled timer and add it to a runloop, then the closure/block that is executed when the timer fires, also fires at creation time.
Am I doing something wrong, or is this a bug?
Thanks.
e.g.
import Foundation
@main
public struct TimerRunloop {
public private(set) var text = "Hello, World!"
public static func main() {
// print(TimerRunloop().text)
let runLoop = RunLoop.current
let distantFuture = Date.distantFuture
/// Set this to false when we want to exit the app...
let shouldKeepRunning = true
// Set a scheduled timer going
print("\(Date()) Program starts.")
let timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { timer in
print("\(Date()) Timer fired.")
}
// Set a timer and add it tp the runloop manually
let timer2 = Timer(timeInterval: 5.0, repeats: true) { timer in
print("\(Date()) Timer2 fired")
}
// Make sure that it is scheduled onto the main thread.
DispatchQueue.main.async {
RunLoop.current.add(timer2, forMode: .default)
}
// Run forever
while shouldKeepRunning == true &&
runLoop.run(mode:.default, before: distantFuture) {}
}
}
Results:
macOS
swift-driver version: 1.62.15 Apple Swift version 5.7.2 (swiftlang-5.7.2.135.5 clang-1400.0.29.51)
Target: x86_64-apple-macosx13.0
2023-03-03 5:32:03 pm +0000 Program starts.
2023-03-03 5:32:08 pm +0000 Timer fired.
2023-03-03 5:32:08 pm +0000 Timer2 fired
2023-03-03 5:32:13 pm +0000 Timer fired.
2023-03-03 5:32:13 pm +0000 Timer2 fired
Linux
Swift version 5.7.2 (swift-5.7.2-RELEASE)
Target: aarch64-unknown-linux-gnu
pi@piPrincedaleSpare:~/swift/TimerRunloop $ swift run
Building for debugging...
[5/5] Linking TimerRunloop
Build complete! (3.24s)
2023-03-03 17:32:52 +0000 Program starts.
2023-03-03 17:32:52 +0000 Timer2 fired
2023-03-03 17:32:57 +0000 Timer fired.
2023-03-03 17:32:57 +0000 Timer2 fired
2023-03-03 17:33:02 +0000 Timer fired.
2023-03-03 17:33:02 +0000 Timer2 fired