处理程序每​​5秒运行一次任务Kotlin

Rya*_*ley 9 android handler runnable kotlin

我想每5秒运行一次代码.我无法通过处理程序实现此目的.怎么能在Kotlin完成?这是我到目前为止所拥有的.另外需要注意的是,变量Timer_Preview是一个Handler.

我的守则

zsm*_*b13 16

由于您无法引用当前所在的lambda,并且在定义要分配给它的lambda时无法引用所定义的属性,因此这里的最佳解决方案是object表达式:

val runnableCode = object: Runnable {
    override fun run() {
        handler.postDelayed(this, 5000)
    }
}
Run Code Online (Sandbox Code Playgroud)

假设此属性不是var因为您实际上想要在发生此自我调用时更改它.


Mor*_*goo 6

简单使用 fixedRateTimer

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

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

  • 不过,别忘了在离开时进行清理,例如在Android上:myFixedRateTimer.cancel() (2认同)

can*_*ler 5

我推荐SingleThread因为它非常有用。如果你想每秒做一次工作,你可以设置它的参数:

Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(Runnable 命令,长initialDelay,长周期,TimeUnit 单位);

TimeUnit 值为:纳秒、微秒、毫秒、秒、分、小时、天。

例子:

private fun mDoThisJob(){

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

    }, 1, 1, TimeUnit.SECONDS)
}
Run Code Online (Sandbox Code Playgroud)