前言
在 Kotlin 中实现定时任务有多种方式:
Timer/TimerTask:简单易用,但功能有限,在多线程环境下可能存在问题。- 协程:Kotlin 推荐方式,非阻塞特性好,内存效率高,适合 Android 等场景。
使用Timer(Java 标准库)
1 | fun startTimerTask() { |
使用Kotlin 协程
延迟执行
1 | import kotlinx.coroutines.* |
循环执行
1 | import kotlinx.coroutines.* |
ViewModel中使用
循环
1 | fun startTimerTask() { |
延迟
1 | init { |
Compose中使用
1 | val showQuesDetail = remember { mutableStateOf(true) } |