如何在Kotlin中使用Timer.scheduleAtFixedRate

7

我是kotlin Android开发的新手。 因此,我想知道如何使用。

inline fun Timer.scheduleAtFixedRate(
    delay: Long,
    period: Long,
    crossinline action: TimerTask.() -> Unit
): TimerTask

指任何示例。

提前感谢。

2个回答

16

试一试

    Timer().schedule(object : TimerTask() {
        override fun run() {
            Log.e("NIlu_TAG","Hello World")
        }
    }, 3000)

或者这一个

Timer().schedule(timerTask {
            Log.e("NIlu_TAG","Hello World")
        }, 3000)

或者这个

    Timer().scheduleAtFixedRate(object : TimerTask() {
        override fun run() {
            Log.e("NIlu_TAG","Hello World")
        }
    },2000,2)

简短回答

Timer().scheduleAtFixedRate(timerTask {
        Log.e("NIlu_TAG","Hello World")
    },2000,2)

2
谢谢,但我想知道如何使用上面的Kotlin内联函数。 - sandeep kolhal
根据理论,您可以在上一个任务开始和下一个任务开始之间安排一个操作,因此您可以通知进度条的进度,并在完成时取消它。您可以使用Kotlin协程实现此操作。 - Jaco

3

你也可以这样做:

val fixedRateTimer = fixedRateTimer(name = "hello-timer",
        initialDelay = 1000, period = 1000,daemon = true) {
        println("Hello")
    }

但是我们该如何开始呢?我在我的viewModel中有这个,我想从Activity中启动它。 - james04

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