As the title, is there any way to call a function after delay (1 second for example) in Kotlin
?
问题:
回答1:
You can use Schedule
inline fun Timer.schedule(
delay: Long,
crossinline action: TimerTask.() -> Unit
): TimerTask (source)
example (thanks @Nguyen Minh Binh - found it here: http://jamie.mccrindle.org/2013/02/exploring-kotlin-standard-library-part-3.html)
Timer("SettingUp", false).schedule(500) {
doSomething()
}
回答2:
There is also an option to use Handler -> postDelayed
Handler().postDelayed({
//doSomethingHere()
}, 1000)
回答3:
You have to import the following two libraries:
import java.util.*
import kotlin.concurrent.schedule
and after that use it in this way:
Timer().schedule(10000){
//do something
}
回答4:
val timer = Timer()
timer.schedule(timerTask { nextScreen() }, 3000)
回答5:
A simple example to show a toast after 3 seconds :
fun onBtnClick() {
val handler = Handler()
handler.postDelayed({ showToast() }, 3000)
}
fun showToast(){
Toast.makeText(context, "Its toast!", Toast.LENGTH_SHORT).show()
}
回答6:
Many Ways
1. Using Handler
class
Handler().postDelayed({
TODO("Do something")
}, 2000)
2. Using Timer
class
Timer().schedule(object : TimerTask() {
override fun run() {
TODO("Do something")
}
}, 2000)
Shorter
Timer().schedule(timerTask {
TODO("Do something")
}, 2000)
Shortest
Timer().schedule(2000) {
TODO("Do something")
}
3. Using Executors
class
Executors.newSingleThreadScheduledExecutor().schedule({
TODO("Do something")
}, 2, TimeUnit.SECONDS)
回答7:
You could launch
a coroutine, delay
it and then call the function:
/*GlobalScope.*/launch {
delay(1000)
yourFn()
}
If you are outside of a class or object prepend GlobalScope
to let the coroutine run there, otherwise it is recommended to implement the CoroutineScope
in the surrounding class, which allows to cancel all coroutines associated to that scope if necessary.
回答8:
If you are looking for generic usage, here is my suggestion:
Create a class named as Run
:
class Run {
companion object {
fun after(delay: Long, process: () -> Unit) {
Handler().postDelayed({
process()
}, delay)
}
}
}
And use like this:
Run.after(1000, {
// print something useful etc.
})