Sleep in Kotlin
This article explores different ways to sleep in Kotlin.
1. Using Thread.sleep() function
To set the current thread to sleep, we can use the Thread.sleep() function. It takes in the total number of milliseconds to sleep, and can be used as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { println("Stopping…") try { // sleep for one second Thread.sleep(1000) } catch (e: InterruptedException) { e.printStackTrace() } println("Resuming…") } |
Output:
Stopping…
Resuming…
2. Using TimeUnit
Alternatively, we can use the sleep() function of TimeUnit which automatically converts the specified time unit into the form required by the Thread.sleep() function. To sleep in seconds, use TimeUnit.SECONDS.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.concurrent.TimeUnit fun main() { println("Stopping…") try { // sleep for one second TimeUnit.SECONDS.sleep(1) } catch (e: InterruptedException) { e.printStackTrace() } println("Resuming…") } |
Output:
Stopping…
Resuming…
Similarly, to sleep in milliseconds, use TimeUnit.MILLISECONDS. The TimeUnit offers a total of 7 Time units i.e, NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, and DAYS.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.concurrent.TimeUnit fun main() { println("Stopping…") try { // sleep for 500 milliseconds TimeUnit.MILLISECONDS.sleep(500) } catch (e: InterruptedException) { e.printStackTrace() } println("Resuming…") } |
Output:
Stopping…
Resuming…
That’s all about sleeping in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)