每5秒运行任务的处理程序 Kotlin

19

我希望每隔5秒运行一次某段代码。 我尝试使用 Handler 实现,但遇到了困难。 在 Kotlin 中应该如何实现? 这是我目前的代码。 值得注意的是,变量 Timer_Preview 是一个 Handler。

我的代码


您可以将 Callable 传递给您的 Handler,并使用 sendMessageDelayed 进行递归。 - holi-java
1
请在问题中放置代码,而不是链接,因为 a) 不是每个人都可以从工作中访问imgur,b) 链接可能会过期,这个问题将来就无用了。 - Todd
谢谢你让我知道! - Ryan Dailey
5个回答

28

由于您无法引用当前所在的lambda表达式,也无法在定义属性时引用分配给它的lambda表达式,因此在这里最好的解决方案是对象表达式

val runnableCode = object: Runnable {
    override fun run() {
        handler.postDelayed(this, 5000)
    }
}

假设这个属性不是一个var,因为在这个自调用发生时你实际上想要改变它。


谢谢,这正是我在寻找的!非常好用。 - Ryan Dailey
我猜你可以创建一个默认的处理程序(即val handler:Handler = Handler()),然后启动它(即handler.post(runnableCode)),并且在每5秒运行run块中放置的所有内容(在handler.postDelayed之前...)? - Mike Miller

20

仅需使用fixedRateTimer

 fixedRateTimer("timer",false,0,5000){
        this@MainActivity.runOnUiThread {
            Toast.makeText(this@MainActivity, "text", Toast.LENGTH_SHORT).show()
        }
    }

通过为第三个参数设置另一个值来更改初始延迟。


4
离开时别忘了清理,例如在Android上:myFixedRateTimer.cancel()。 - Andrei Drynov

5
我推荐使用SingleThread,因为它非常实用。如果您希望每秒钟执行一次作业,您可以设置以下参数:

Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);

时间单位包括:NANOSECONDS(纳秒)、MICROSECONDS(微秒)、MILLISECONDS(毫秒)、SECONDS(秒)、MINUTES(分钟)、HOURS(小时)和DAYS(天)。 示例:
private fun mDoThisJob(){

    Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate({
        //TODO: You can write your periodical job here..!

    }, 1, 1, TimeUnit.SECONDS)
}

3
由于Kotlin尚未允许递归lambda(参见KT-10350),因此您必须使用其他结构,例如@zsmb13答案中的对象表达式,或下面的普通函数。
fun StartTimer() {
    Timer_Preview.postDelayed(Runnable { runnable() }, 5000)
}

fun runnable() {
    //Code here

    // Run code again after 5 seconds
    Timer_Preview.postDelayed(Runnable { runnable() }, 5000)
}

然而,在你的特定情况中,看起来你可以只需再次调用StartTimer()来重新启动计时器,假设它不会执行其他任何操作:

private val RunnableCode = Runnable {
    //Code here

    //Run code again after 5 seconds
    StartTimer()
}

0

您可以使用简单的函数来实现这个功能:

private fun waitToDoSomethingRecursively() {
    handler.postDelayed(::doSomethingRecursively, 5000)
}

private fun doSomethingRecursively () {
    ...
    waitToDoSomethingRecursively()
}

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