Skip to content

Instantly share code, notes, and snippets.

@gmk57
Last active September 16, 2024 13:55
Show Gist options
  • Save gmk57/67591e0c878cedc2a318c10b9d9f4c0c to your computer and use it in GitHub Desktop.
Save gmk57/67591e0c878cedc2a318c10b9d9f4c0c to your computer and use it in GitHub Desktop.
Coroutine-based solution for delayed and periodic work
/**
* Coroutine-based solution for delayed and periodic work. May fire once (if [interval] omitted)
* or periodically ([startDelay] defaults to [interval] in this case), replacing both
* `Observable.timer()` & `Observable.interval()` from RxJava.
*
* In contrast to RxJava, intervals are calculated since previous run completion; this is more
* convenient for potentially long work (prevents overlapping) and does not suffer from queueing
* multiple invocations in Doze mode on Android.
*
* Dispatcher is inherited from scope, may be overridden via [context] parameter.
*
* Inspired by [https://github.com/Kotlin/kotlinx.coroutines/issues/1186#issue-443483801]
*/
@ExperimentalTime
fun CoroutineScope.timer(
interval: Duration = Duration.ZERO,
startDelay: Duration = interval,
context: CoroutineContext = EmptyCoroutineContext,
block: suspend () -> Unit
): Job = launch(context) {
delay(startDelay)
do {
block()
delay(interval)
} while (interval > Duration.ZERO)
}
/** Variant of [timer] with intervals (re)calculated since the beginning (like in RxJava), for cases
* where accumulating time shift due to [delay] non-exactness & time spent in [block] is undesirable */
@ExperimentalTime
fun CoroutineScope.timerExact(
interval: Duration = Duration.ZERO,
startDelay: Duration = interval,
context: CoroutineContext = EmptyCoroutineContext,
block: suspend () -> Unit
): Job = launch(context) {
val startTime = TimeSource.Monotonic.markNow()
var count: Long = 0
delay(startDelay)
do {
block()
// Long to Double conversion is generally lossy, but values up to 2^53 (285 million years
// for 1-second intervals) will be represented exactly, see https://stackoverflow.com/a/1848762
val nextTime = startTime + startDelay + interval * (++count).toDouble()
delay(nextTime.remaining())
} while (interval > Duration.ZERO)
}
/** Returns the amount of time remaining until this mark (opposite of [TimeMark.elapsedNow]) */
@ExperimentalTime
fun TimeMark.remaining(): Duration = -elapsedNow()
@IkemNwodo
Copy link

Thank you so much for taking the time to explain. I found recursion to be more suited for the problem I was trying to fix.

@gmk57
Copy link
Author

gmk57 commented Apr 30, 2022

Sure, it depends on your use case. If you're just retrying some operation on failure, you may find my runRetrying useful. For more tricky cases recursion seems to be an elegant solution, but please be aware that with infinite retries it causes a memory leak and will crash sooner or later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment