Florian
08/24/2021, 6:37 PMlaunch
block around taskDao.increaseMillisCompletedToday
(which is a database operation) look dangerous? I use this to measure time but without the nested launch
, I think the length of the database operation itself is causing imprecision. The tick interval is every 1s.
fun startTimer() {
timerJob?.cancel()
timerJob = applicationScope.launch {
val selectedTask = selectedTask.first()
if (selectedTask != null) {
taskDao.updateLastActiveTimestamp(selectedTask.id, System.currentTimeMillis())
startTimerService()
timerRunningFlow.value = true
while (true) {
val timeBefore = SystemClock.elapsedRealtime()
delay(TICK_DELAY)
val timeAfter = SystemClock.elapsedRealtime()
val elapsedTime = timeAfter - timeBefore
launch {
taskDao.increaseMillisCompletedToday(selectedTask.id, elapsedTime)
}
}
}
}
}
groostav
08/24/2021, 7:40 PMDelay
works as ScheduledExecutorService.scheduleWithFixedDelay
where Im guessing what you want is ScheduledExecutorService.scheduleAtFixedRate
Florian
08/24/2021, 7:58 PMNick Allen
08/24/2021, 11:05 PMval startTime = SystemClock.elapsedRealtime()
var lastReportedTime = 0
while(true) {
delay(TICK_DELAY)
val totalElapsedTime = SystemClock.elapsedRealtime() - startTime
taskDao.increaseMillisCompletedToday(selectedTask.id, totalElapsedTime - lastReportedTime)
lastReportedTime = totalElapsedTime
}
Florian
08/24/2021, 11:24 PM