如何创建一个简单的计时器来使用setInterval每秒执行一个有趣的事情?

我是Kotlin的新手。 我想创建一个简单的计时器来执行每一秒的fun 。 我研究了一些方法,并find了setInterval 。 但我不明白如何在代码中实现。 我只需要每秒执行println("Hello, world!")

我不知道setInterval(注意,它只是JS平台!),但如果你想打印“Hello world!” 每秒钟,这里是一个解决方案

 fun doEverySeconds(action: () -> Unit) { thread { while (true) { action() Thread.sleep(1000) } } } 

那么你可以像这样使用它

 fun main(args: Array) { doEverySeconds { println("Hello world !") } } 

或者以时间作为参数

 fun doEveryX(timeInMS : Long, action: () -> Unit) { thread { while (true) { action() Thread.sleep(timeInMS) } } } fun main(args: Array) { doEveryX(1200) { println("Hello world !") } } 

要添加到user3491043的答案,我想指出,你可以使用协程 Java的Timer#scheduleAtFixedRate

以下是使用协程的示例:

 async { while (true) { // Do whatever delay(interval) } }