I have encapsulated a while that waits for 8 hours to end. I need to repeat the task in it until the time reaches 8 hours. How can I make while wait for my task to end before starting the next cycle, instead of a fixed delay time?
fun startPeriodicTask(timeout: Long, block: suspend CoroutineScope.() -> Unit) {
periodicTask = viewModelScope.launcher {
while (dataService.timeConfigData.runTime.value!!.toLong() < dataService.timeConfigData.timeEnd.value!!.toLong()) {
withTimeout(timeout) {
// 执行任务
XLog.v("startPeriodicTask run block")
block()
}
delay(timeout)
}
}
}
vm.startPeriodicTask(2000) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mVibrator?.vibrate(VibrationEffect.createOneShot(1000, 255))
} else {
mVibrator?.vibrate(longArrayOf(1000, 2000), 1)
}
}
My understanding is that this is not feasible, because the coroutine is a recursive process, so when I suspend it, I can’t wait, and the main thread is blocked.