Skip to content

Instantly share code, notes, and snippets.

@Tea-Ayataka
Created September 15, 2018 08:54
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tea-Ayataka/97920f95927b43a375e07ca3d248ad9e to your computer and use it in GitHub Desktop.
Save Tea-Ayataka/97920f95927b43a375e07ca3d248ad9e to your computer and use it in GitHub Desktop.
Kotlin Coroutine Timer
package net.ayataka.bas.utils
import kotlinx.coroutines.experimental.*
import net.ayataka.bas.LOGGER
import kotlin.system.measureTimeMillis
fun CoroutineScope.timer(interval: Long, fixedRate: Boolean = true, action: suspend TimerScope.() -> Unit): Job {
return launch {
val scope = TimerScope()
while (true) {
val time = measureTimeMillis {
try {
action(scope)
} catch (ex: Exception) {
LOGGER.error("LWTimer task", ex)
}
}
if (scope.isCanceled) {
break
}
if (fixedRate) {
delay(Math.max(0, interval - time))
} else {
delay(interval)
}
yield()
}
}
}
class TimerScope {
var isCanceled: Boolean = false
private set
fun cancel() {
isCanceled = true
}
}
fun CoroutineScope.start(block: suspend CoroutineScope.() -> Unit) {
launch(block = block)
}
@raydenvoldeskine
Copy link

Would you add an example call of this timer?

@Tea-Ayataka
Copy link
Author

I'll recode this as a repository. @fracturizer

@xxhdpi
Copy link

xxhdpi commented Apr 11, 2021

@Tea-Ayataka any update for these implementation ??

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