Skip to content

Instantly share code, notes, and snippets.

@meoyawn
Created Dec 30, 2019
Embed
What would you like to do?
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.time.delay
import mu.KotlinLogging
import java.time.Duration
private val log = KotlinLogging.logger { }
data class PeriodicJob(
val initialDelay: () -> Duration = { Duration.ZERO },
val work: suspend () -> Duration
)
fun CoroutineScope.launch(job: PeriodicJob): Job =
launch {
delay(job.initialDelay())
while (true) {
val next = try {
job.work()
} catch (e: Exception) {
log.error { e }
Duration.ZERO
}
delay(next)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment