Created
September 15, 2018 08:54
-
-
Save Tea-Ayataka/97920f95927b43a375e07ca3d248ad9e to your computer and use it in GitHub Desktop.
Kotlin Coroutine Timer
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
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would you add an example call of this timer?