Hi, I need a CoroutineDispatcher on Android that w...
# coroutines
m
Hi, I need a CoroutineDispatcher on Android that will make
delay
wait for given real time, not CPU time. I'm assuming that default implementation doesn't take CPU sleep into account, I'm I right? If during 5min delay CPU sleeps for 15 min, will delay effectively take 20min?
I don't expect delay expiring to wake the CPU, just that it executes soon after CPU wakes from sleep if needed.
o
delay
depends on the Dispatcher, so it probably differs if you're talking about
Dispatcher.Main
vs
Dispatcher.Default
. iirc
Main
tends to use the platform's waiting utilities, so on android that's `Handler`: https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/kotlinx-coroutines-android/src/HandlerDispatcher.kt#L139
I think
Default
uses
System.nanoTime()
on android, which probably is CPU time as well
you probably should use
suspendCancellableCoroutine
in addition to
AlarmManager
+ https://developer.android.com/reference/android/app/AlarmManager.html#ELAPSED_REALTIME , or if you need it more ingrained, write a new dispatcher on top of that.
m
AlarmManager seems like an overkill, but I'm not sure how to benchmark it against some alternative
o
the only alternative I could think of (haven't used android a bunch) would be to spin on https://developer.android.com/reference/android/os/SystemClock.html#elapsedRealtime() , which I would think is much less efficient than AlarmManager
s
Depending on how precise you need this job to run I'd recommend either AlarmManager (for precision at the cost of battery life) or WorkManager (for a more optimized yet less precisely timed execution)
Can you give more details about what you want to accomplish with this task?
m
I'm doing some minute-by-minute stats of data flowing though my VPN. I was thinking I can either check the time for each data packet (maybe over 10k times a second) or I can have a 1 min timer to do the same. Only issue is that I can't get proper timer without some heavy IPC APIs.