Search code examples
swiftlinuxswift-package-manager

How to thread sleep in swift on linux


I am trying to write a small program that runs on a loop and executes some code every 30 seconds.

I don't care very much about it being exact on the timing, but I do care that the program can compile & run on a linux platform, and that it can be built & tested using the swift package manager.

My first shot was like

while true {
    print("doing the work")
    sleep(30) // also tried usleep(30*1000*1000)
}

Apparently there is no reference to sleep(_:) in swift 4 that I can find, and that code does not compile. I have tried to use a Timer, but the program exits as soon as the timer starts ticking because the timer runs in the background and the main thread's only job is to schedule it.

This has to be easier than it seems. What am I missing about thread management in Swift that would explain how hard I find this?

--- EDIT To clarify why this is different from numerous suggested duplicates:

I am explicitly trying to sleep the main thread, and as I mentioned above, I had been unable to get Swift on Linux to compile using the sleep function suggested by the accepted answers elsewhere. The context of my program in a CLI context means that delayed actions in background thread, as suggested by numerous other sources available, will not work here. Additionally, this CLI is running on Linux, and so I can't depend on iOS-only libraries.


Solution

  • You can import sleep from Glibc or Darwin, but better yet, you can use Thread.sleep(forTimeInterval:) from Foundation

    import Foundation
    
    while true {
        print("hello")
        Thread.sleep(forTimeInterval: 0.1)
    }