如何在 Kotlin 中设置延迟?

7

我希望等待2到3秒钟,我知道在Java中该如何实现并已尝试过,但不清楚如何在Kotlin中实现。

类似以下简单的示例:

println("hello")
// a 2 seconds delay
println("world")

3
你尝试了什么?发生了什么事情? - Code-Apprentice
这个回答解决了你的问题吗?Kotlin - Wait function - Bink
4个回答

14

很简单,只需使用协程。就像这样:

fun main() = runBlocking { 
    launch { 
        delay(2000L)
        println("World!") 
    }
    println("Hello")
}

别忘了像这样导入Kotlin协程:

import kotlinx.coroutines.*

在Kotlin中愉快地编程!!!


你为什么想要运行这个阻塞的程序?如果延迟更大,同时你退出应用程序会发生什么? - David

5

有一些方法:

1- 使用Handler(基于毫秒)(已弃用):

println("hello")
Handler().postDelayed({
   println("world")
}, 2000)

2- 通过使用 Executors(基于第二种方法):

println("hello")
Executors.newSingleThreadScheduledExecutor().schedule({
    println("world")
}, 2, TimeUnit.SECONDS)

3- 通过使用基于毫秒的计时器:

println("hello")
Timer().schedule(2000) {
  println("world")
}

0

使用:

viewmodelScope.launch {
    println("hello")
    delay(2000)
    println("world")
}

如果应用程序在您的延迟运行时转到后台,println("world") 仍将运行,这是您想要的吗? - David

-1

如果您不想使用任何依赖项,那么可以使用Thread.sleep(2000L)。 这里,1秒=1000L 代码应该像这样:

println("hello")
Thread.sleep(2000L)
println("world")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接