krontab/src/commonMain/kotlin/com/insanusmokrassar/krontab/utils/SchedulerFlow.kt

26 lines
764 B
Kotlin
Raw Normal View History

2020-01-13 04:15:01 +00:00
package com.insanusmokrassar.krontab.utils
import com.insanusmokrassar.krontab.KronScheduler
import com.soywiz.klock.DateTime
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)
val sleepDelay = (nextTime - now).millisecondsLong
delay(sleepDelay)
collector.emit(nextTime)
}
}
}