作为标题,在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);
时间单位值是:纳秒,微秒,毫秒,秒,分钟,小时,天。
其他回答
你可以使用日程安排
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()
}
如果你在寻找通用用法,下面是我的建议:
创建一个名为Run的类:
class Run {
companion object {
fun after(delay: Long, process: () -> Unit) {
Handler().postDelayed({
process()
}, delay)
}
}
}
像这样使用:
Run.after(1000, {
// print something useful etc.
})
还有一个选项使用Handler -> postDelayed
Handler().postDelayed({
//doSomethingHere()
}, 1000)
我推荐使用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);
时间单位值是:纳秒,微秒,毫秒,秒,分钟,小时,天。
val timer = Timer()
timer.schedule(timerTask { nextScreen() }, 3000)
推荐文章
- 如何模拟Android杀死我的进程
- 禁用EditText闪烁光标
- Android Eclipse -无法找到*.apk
- 设置TextView文本从html格式的字符串资源在XML
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- 如何克隆或复制一个列表在kotlin
- Android加载JS包失败
- Android Studio, logcat在应用程序关闭后清理
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的
- 在Mac OS X上哪里安装Android SDK ?
- 我如何获得图像缩放功能?
- 在Android应用程序中显示当前时间和日期