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


当前回答

我推荐使用SingleThread,因为你不需要在使用后杀死它。此外,“stop()”方法在Kotlin语言中已弃用。

private fun mDoThisJob(){

    Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate({
        //TODO: You can write your periodical job here..!

    }, 1, 1, TimeUnit.SECONDS)
}

此外,您可以使用它定期工作。它非常有用。如果你想在每一秒内完成一个任务,你可以设置它的参数:

Executors.newSingleThreadScheduledExecutor()。scheduleAtFixedRate(可运行命令,长initialDelay,长周期,TimeUnit unit);

时间单位值是:纳秒,微秒,毫秒,秒,分钟,小时,天。

其他回答

我建议使用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()

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

创建一个名为Run的类:

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

像这样使用:

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

你可以启动一个协程,延迟它,然后调用函数:

 /*GlobalScope.*/launch {
   delay(1000)
   yourFn()
 }

如果你在类或对象的外部,让协程在那里运行,否则建议在周围的类中实现CoroutineScope,这允许在必要时取消与该作用域关联的所有协程。

val timer = Timer()
timer.schedule(timerTask { nextScreen() }, 3000)

如果你正在使用最新的Android api, Handler空构造函数已经被弃用,你应该包括一个循环程序。你可以很容易地通过loop . getmainlooper()得到一个。

    Handler(Looper.getMainLooper()).postDelayed({
        //Your code
    }, 2000) //millis