作为标题,在Kotlin中是否有方法在延迟(例如1秒)后调用函数?


当前回答

另一种创造冗余工作的方法;这并不要求函数挂起。

   val repeatableJob = CoroutineScope(Dispatchers.IO).launch {
        while (true) {
            delay(1000)
        }
    }

完成后取消- repeatableJob.cancel ()

其他回答

如果你在寻找通用用法,下面是我的建议:

创建一个名为Run的类:

class Run {
    companion object {
        fun after(delay: Long, process: () -> Unit) {
            Handler().postDelayed({
                process()
            }, delay)
        }
    }
}

像这样使用:

Run.after(1000, {
    // print something useful etc.
})

你可以使用日程安排

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

例子(谢谢@Nguyen Minh Binh -在这里找到它:http://jamie.mccrindle.org/2013/02/exploring-kotlin-standard-library-part-3.html)

import java.util.Timer
import kotlin.concurrent.schedule

Timer("SettingUp", false).schedule(500) { 
   doSomething()
}

我建议使用kotlin协程,如果你想取消它。它结构简单,重量轻。

fun repeatFun(): Job {
    return coroutineScope.launch {  
        while(isActive) {
            //do your work here
            delay(1000)
        }
    }
}

//start the loop
val repeatFun = repeatRequest()

//Cancel the loop
repeatFun.cancel()
val timer = Timer()
timer.schedule(timerTask { nextScreen() }, 3000)

一个简单的例子来展示3秒后的祝酒词:

fun onBtnClick() {
    val handler = Handler()
    handler.postDelayed({ showToast() }, 3000)
}

fun showToast(){
    Toast.makeText(context, "Its toast!", Toast.LENGTH_SHORT).show()
}