com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions.CalculatedDateTime.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of AutoPostTelegramBot Show documentation
Show all versions of AutoPostTelegramBot Show documentation
It is base library for creating smart bot for simple management of channels posts
package com.github.insanusmokrassar.AutoPostTelegramBot.utils.extensions
import com.github.insanusmokrassar.AutoPostTelegramBot.utils.CalculatedDateTime
import kotlinx.coroutines.experimental.*
import org.joda.time.DateTime
typealias CalculatedPeriod = Pair
fun Iterable.launchNearFuture(block: suspend () -> R): Deferred? {
var dateTimeToTrigger: DateTime? = null
forEach {
val currentAsFuture = it.asFuture
if (dateTimeToTrigger == null || currentAsFuture.isBefore(dateTimeToTrigger)) {
dateTimeToTrigger = currentAsFuture
}
}
return dateTimeToTrigger ?.let {
async {
delay(it.millis - System.currentTimeMillis())
block()
}
}
}
fun Iterable.asPairs(): List {
var first: CalculatedDateTime? = null
val result = mutableListOf()
forEach {
first = first ?.let {
currentFirst ->
result.add(currentFirst to it)
null
} ?: it.let {
_ ->
it
}
}
return result
}
fun CalculatedPeriod.isBetween(dateTime: DateTime): Boolean {
val secondDateTime = second.asFutureFor(dateTime)
var firstDateTime = first.asPastFor(secondDateTime)
return dateTime.isAfter(firstDateTime) && dateTime.isBefore(secondDateTime)
}
val CalculatedPeriod.nowIsBetween: Boolean
get() = isBetween(DateTime.now())