Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.sleep() in a native Kotlin project

I'm trying to create a simple native Kotlin project. I want my project to wait for X millisec during a process:

import kotlin.concurrent

fun main() {
    Thread.sleep(500);
    println("Hello world")
}

Command to compile:

kotlinc main.kt -o program.exe

But I get the following error:

main.kt:1:15: error: unresolved reference: concurrent
import kotlin.concurrent
              ^
main.kt:4:2: error: unresolved reference: Thread
        Thread.sleep(500);
        ^

I'm a bit confused, isn't this the proper way to delay my application?

like image 400
birgersp Avatar asked Oct 27 '25 00:10

birgersp


1 Answers

If you need to be more precise than just seconds, you can use the the nanosleep function like this:

import platform.posix.nanosleep
import platform.posix.timespec

// ...

val time = cValue<timespec> {
    tv_sec = 2
    tv_nsec = 500000000
}

nanosleep(time, null)
  • tv_sec is the amount of seconds to sleep
  • tv_nsec is the additional amount of nanoseconds to sleep (0 to 999999999)

The example above waits 2.5 seconds.

like image 79
Nicofisi Avatar answered Oct 29 '25 16:10

Nicofisi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!