Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Timer behaviour is incorrect on Linux when using init(timeInterval: TimeInterval, repeats: Bool, block: (Timer) -> Void) #4712

Open
Diggory opened this issue Mar 4, 2023 · 0 comments

Comments

@Diggory
Copy link

Diggory commented Mar 4, 2023

Hello,

https://forums.swift.org/t/timer-behaviour-different-on-linux-and-macos-timer-block-executed-upon-timer-creation-too-early/63509

The Timer initialiser init(timeInterval: TimeInterval, repeats: Bool, block: (Timer) -> Void) behaves wrongly on Linux.

if the user creates a non-scheduled timer and adds it to a runloop, the closure/block that is executed when the timer fires, also fires at creation time.

Demonstration Code


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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant