diff --git a/CHANGELOG.md b/CHANGELOG.md index 93f840e..23feab0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## 0.4.1 +* Add `CollectionKronScheduler`. It will give opportunity to unite several schedulers in one + ## 0.4.0 **BREAKING CHANGES** diff --git a/src/commonMain/kotlin/dev/inmo/krontab/collection/CollectionFunctions.kt b/src/commonMain/kotlin/dev/inmo/krontab/collection/CollectionFunctions.kt new file mode 100644 index 0000000..44b03a2 --- /dev/null +++ b/src/commonMain/kotlin/dev/inmo/krontab/collection/CollectionFunctions.kt @@ -0,0 +1,25 @@ +package dev.inmo.krontab.collection + +import dev.inmo.krontab.KronScheduler + +@Suppress("NOTHING_TO_INLINE") +inline fun CollectionKronScheduler.includeAll(kronSchedulers: List) { + kronSchedulers.forEach { + include(it) + } +} + +@Suppress("NOTHING_TO_INLINE") +inline fun CollectionKronScheduler.includeAll(vararg kronSchedulers: KronScheduler) { + includeAll(kronSchedulers.toList()) +} + +operator fun KronScheduler.plus(kronScheduler: KronScheduler): CollectionKronScheduler { + return CollectionKronScheduler().apply { + includeAll(this, kronScheduler) + } +} + +operator fun CollectionKronScheduler.plusAssign(kronScheduler: KronScheduler) { + include(kronScheduler) +} diff --git a/src/commonMain/kotlin/dev/inmo/krontab/collection/CollectionKronScheduler.kt b/src/commonMain/kotlin/dev/inmo/krontab/collection/CollectionKronScheduler.kt new file mode 100644 index 0000000..e819d16 --- /dev/null +++ b/src/commonMain/kotlin/dev/inmo/krontab/collection/CollectionKronScheduler.kt @@ -0,0 +1,41 @@ +package dev.inmo.krontab.collection + +import com.soywiz.klock.DateTime +import dev.inmo.krontab.KronScheduler +import dev.inmo.krontab.anyCronDateTime +import dev.inmo.krontab.internal.CronDateTimeScheduler +import dev.inmo.krontab.internal.toNearDateTime + +data class CollectionKronScheduler private constructor( + internal val schedulers: MutableList +) : KronScheduler { + internal constructor(schedulers: List) : this(schedulers.toMutableList()) + internal constructor() : this(mutableListOf()) + + fun include(kronScheduler: KronScheduler) { + when (kronScheduler) { + is CronDateTimeScheduler -> { + val resultCronDateTimes = kronScheduler.cronDateTimes.toMutableList() + schedulers.removeAll { + if (it is CronDateTimeScheduler) { + resultCronDateTimes.addAll(it.cronDateTimes) + true + } else { + false + } + } + schedulers.add( + CronDateTimeScheduler(resultCronDateTimes.distinct()) + ) + } + is CollectionKronScheduler -> kronScheduler.schedulers.forEach { + include(it) + } + else -> schedulers.add(kronScheduler) + } + } + + override suspend fun next(relatively: DateTime): DateTime { + return schedulers.minOfOrNull { it.next(relatively) } ?: anyCronDateTime.toNearDateTime(relatively) + } +}