Skip to content

Instantly share code, notes, and snippets.

@ccampo133
Last active January 20, 2021 04:13
Show Gist options
  • Save ccampo133/7331b84fe5383f96c10d99b05370d319 to your computer and use it in GitHub Desktop.
Save ccampo133/7331b84fe5383f96c10d99b05370d319 to your computer and use it in GitHub Desktop.
Infinite retry with exponential backoff in Kotlin using co-routines
/**
* Copyright 2018 C.J. Campo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
import kotlinx.coroutines.experimental.delay
import java.util.concurrent.TimeUnit
suspend fun <T> infiniteRetry(
maxWait: Long = 10,
unit: TimeUnit = TimeUnit.SECONDS,
factor: Double = 1.0,
onError: (Attempt) -> Unit = {},
task: suspend () -> T
): T {
var attempt = 0L
var wait = 0L
while (true) {
try {
return task()
} catch (e: Exception) {
onError(Attempt(attempt, wait, e))
}
delay(wait)
wait = computeWaitTime(factor, unit.toMillis(maxWait), attempt)
++attempt
}
}
fun computeWaitTime(multiplier: Double, maxWait: Long, attempt: Long): Long {
val exp = Math.pow(2.0, attempt.toDouble())
val result = Math.round(multiplier * exp).coerceAtMost(maxWait)
return if (result >= 0L) result else 0L
}
data class Attempt(val num: Long, val wait: Long, val e: Exception)
/*
* Example usage:
*
* infiniteRetry(onError = { attempt: Attempt -> handleError(attempt, ...) }) {
* doSomething(...)
* }
*
*/
@shharma-vipin
Copy link

you may use delay from - import kotlinx.coroutines.delay

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