Skip to content

Instantly share code, notes, and snippets.

@meoyawn
Created December 30, 2019 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meoyawn/3ff01cbfa698501b3e3c5af7c2b033d1 to your computer and use it in GitHub Desktop.
Save meoyawn/3ff01cbfa698501b3e3c5af7c2b033d1 to your computer and use it in GitHub Desktop.
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