【发布时间】:2022-11-29 14:22:04
【问题描述】:
我想按顺序运行多个计时器。当一个计时器完成时,下一个应该开始。我想过使用 Handler 类,但这具有并行运行计时器的效果。从下面的输出可以看出。
有没有办法让 Timer 操作阻塞线程直到它完成或者有更好的方法来实现这个?也许使用 Futures 或 Kotlin Coroutines?
我是安卓新手。在 iOS 上,我可以使用 OperationQueue/Operation(set isAsynchronous = true) 来做到这一点。
class SequentialTimerTasks {
private val handlerThread: HandlerThread = HandlerThread("HandlerThread")
private lateinit var threadHandler: Handler
class TimerCountTask(private val id: Int) : TimerTask() {
private val TAG = "TimerCountTask"
var count = 0
override fun run() {
Log.d(TAG, "Runnable $id RUNNING TIMER $count")
count++
if (count >=10) {
Log.d(TAG, "Runnable $id CANCEL TIMER $count")
this.cancel()
}
}
}
class RunnableTask(private val id: Int) : Runnable {
private val TAG = "RunnableTask"
override fun run() {
Log.d(TAG, "Runnable $id run() called")
val timer = Timer()
timer.schedule(TimerCountTask(id), 0, 1000)
}
}
fun start() {
handlerThread.start()
threadHandler = Handler(handlerThread.looper)
threadHandler.post(RunnableTask(1))
threadHandler.post(RunnableTask(2))
}
}
输出
Runnable 1 run() called
Runnable 2 run() called
Runnable 1 RUNNING TIMER 0
Runnable 2 RUNNING TIMER 0
Runnable 2 RUNNING TIMER 1
Runnable 1 RUNNING TIMER 1
Runnable 2 RUNNING TIMER 2
Runnable 1 RUNNING TIMER 2
Runnable 2 RUNNING TIMER 3
Runnable 1 RUNNING TIMER 3
Runnable 2 RUNNING TIMER 4
Runnable 1 RUNNING TIMER 4
Runnable 2 RUNNING TIMER 5
Runnable 1 RUNNING TIMER 5
Runnable 2 RUNNING TIMER 6
Runnable 1 RUNNING TIMER 6
Runnable 2 RUNNING TIMER 7
Runnable 1 RUNNING TIMER 7
【问题讨论】:
-
我认为您需要创建“队列事件”在工作线程上执行指定的 Runnable。
-
您只想要基于处理程序的解决方案,还是可以使用 Kotlin 协程?
-
@ArpitShukla 协程将是一个不错的选择。我一直在阅读它们,但不确定如何按顺序实现多个计时器/重复任务
-
你在你的代码中使用 android ViewModels 吗?
-
不,我只是将它作为一个没有生命周期或其他平台依赖性的简单对象运行
标签: android multithreading kotlin timer kotlin-coroutines