krontab/src/commonMain/kotlin/dev/inmo/krontab/utils/SchedulerFlow.kt

26 lines
749 B
Kotlin
Raw Normal View History

2020-11-21 08:58:19 +00:00
package dev.inmo.krontab.utils
2020-01-13 04:15:01 +00:00
import com.soywiz.klock.DateTime
2020-11-21 08:58:19 +00:00
import dev.inmo.krontab.KronScheduler
2020-03-22 12:35:25 +00:00
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.delay
2020-01-13 04:15:01 +00:00
import kotlinx.coroutines.flow.*
@FlowPreview
fun KronScheduler.asFlow(): Flow<DateTime> = SchedulerFlow(this)
@FlowPreview
class SchedulerFlow(
private val scheduler: KronScheduler
) : AbstractFlow<DateTime>() {
@FlowPreview
override suspend fun collectSafely(collector: FlowCollector<DateTime>) {
while (true) {
val now = DateTime.now()
val nextTime = scheduler.next(now) ?: break
2020-01-13 04:15:01 +00:00
val sleepDelay = (nextTime - now).millisecondsLong
delay(sleepDelay)
collector.emit(nextTime)
}
}
}