Programing

Kotlin에서 지연 후 함수를 호출하는 방법은 무엇입니까?

crosscheck 2020. 8. 20. 07:35
반응형

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

반응형