Created
December 30, 2019 14:19
-
-
Save meoyawn/3ff01cbfa698501b3e3c5af7c2b033d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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