krontab/src/commonMain/kotlin/com/insanusmokrassar/krontab/Executes.kt

54 lines
1.6 KiB
Kotlin
Raw Normal View History

package com.insanusmokrassar.krontab
2019-10-05 10:34:59 +00:00
2019-10-10 10:43:52 +00:00
import com.soywiz.klock.DateTime
2020-06-03 15:53:55 +00:00
import kotlinx.coroutines.Deferred
2019-10-10 10:43:52 +00:00
import kotlinx.coroutines.delay
2020-06-03 15:53:55 +00:00
/**
* Execute [block] once at the [KronScheduler.next] time and return result of [block] calculation.
*
* WARNING!!! If you want to launch it in parallel, you must do this explicit.
*/
suspend inline fun <T> KronScheduler.doOnce(noinline block: suspend () -> T): T {
delay((next() - DateTime.now()).millisecondsLong)
return block()
}
/**
* Will [createSimpleScheduler] using [scheduleConfig] and call [doOnce] on it
*/
suspend inline fun <T> doOnce(
scheduleConfig: String,
noinline block: suspend () -> T
) = createSimpleScheduler(scheduleConfig).doOnce(block)
/**
* Will execute [block] while it will return true as a result of its calculation
*/
2019-10-10 10:43:52 +00:00
suspend inline fun KronScheduler.doWhile(noinline block: suspend () -> Boolean) {
2020-06-03 15:53:55 +00:00
do { val doNext = doOnce(block) } while (doNext)
2019-10-10 10:43:52 +00:00
}
2020-06-03 15:53:55 +00:00
/**
* Will [createSimpleScheduler] using [scheduleConfig] and call [doWhile] with [block]
*/
2019-10-10 10:43:52 +00:00
suspend inline fun doWhile(
scheduleConfig: String,
noinline block: suspend () -> Boolean
) = createSimpleScheduler(scheduleConfig).doWhile(block)
2020-06-03 15:53:55 +00:00
/**
* Will execute [block] without any checking of result
*/
2019-10-10 10:43:52 +00:00
suspend inline fun KronScheduler.doInfinity(noinline block: suspend () -> Unit) = doWhile {
2019-10-05 10:34:59 +00:00
block()
true
}
2020-06-03 15:53:55 +00:00
/**
* Will [createSimpleScheduler] using [scheduleConfig] and call [doInfinity] with [block]
*/
2019-10-10 10:43:52 +00:00
suspend inline fun doInfinity(
scheduleConfig: String,
noinline block: suspend () -> Unit
2019-10-10 10:43:52 +00:00
) = createSimpleScheduler(scheduleConfig).doInfinity(block)