How to call a function after delay in Kotlin?

前端 未结 11 1926
南笙
南笙 2020-11-30 19:07

As the title, is there any way to call a function after delay (1 second for example) in Kotlin?

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 19:57

    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)
    

提交回复
热议问题