Kotlin에서 지연 후 함수를 호출하는 방법은 무엇입니까?
제목으로 지연 후 (예 : 1 초) 함수를 호출 할 수있는 방법이 Kotlin
있습니까?
일정 을 사용할 수 있습니다.
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()
}
사용 옵션도 있습니다. Handler -> postDelayed
Handler().postDelayed({
//doSomethingHere()
}, 1000)
여러 가지 방법
1. Handler
수업 사용
Handler().postDelayed({
TODO("Do something")
}, 2000)
2. Timer
수업 사용
Timer().schedule(object : TimerTask() {
override fun run() {
TODO("Do something")
}
}, 2000)
짧게
Timer().schedule(timerTask {
TODO("Do something")
}, 2000)
최단
Timer().schedule(2000) {
TODO("Do something")
}
3. Executors
수업 사용
Executors.newSingleThreadScheduledExecutor().schedule({
TODO("Do something")
}, 2, TimeUnit.SECONDS)
다음 두 라이브러리를 가져와야합니다.
import java.util.*
import kotlin.concurrent.schedule
그 후에 다음과 같이 사용하십시오.
Timer().schedule(10000){
//do something
}
val timer = Timer()
timer.schedule(timerTask { nextScreen() }, 3000)
launch
코 루틴 이 될 수 있고, delay
그런 다음 함수를 호출 할 수 있습니다.
/*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.
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()
}
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.
})
참고URL : https://stackoverflow.com/questions/43348623/how-to-call-a-function-after-delay-in-kotlin
'Programing' 카테고리의 다른 글
종료 날짜가 jQuery를 사용하여 시작 날짜보다 큰지 확인하십시오. (0) | 2020.08.20 |
---|---|
프로그래밍 방식으로 ngClick을 트리거하는 방법 (0) | 2020.08.20 |
WPF에 DesignMode 속성이 있습니까? (0) | 2020.08.19 |
기존 문자열에 추가 (0) | 2020.08.19 |
async : false를 $ .getJSON 호출로 설정할 수 있습니까? (0) | 2020.08.19 |