All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ubertob.pesticide.core.Eventually.kt Maven / Gradle / Ivy

There is a newer version: 1.6.6
Show newest version
package com.ubertob.pesticide.core

import java.time.Clock
import java.time.Duration


//Note expectation should be an operation that takes less then the within duration
inline fun  eventually(within: Duration, expectation: () -> T): T {

    val intervals: Iterator = fibonacci().iterator()
    val chrono = Chrono()
    while (true) {
        try {
            return expectation()
        } catch (t: Throwable) {
            if (chrono.hasTimedOut(within))
                throw t
        }
        Thread.sleep(intervals.next())
    }
}

fun fibonacci(): Sequence = generateSequence(1L to 1L, { it.second to (it.second + it.first) }).map { it.first }


data class Chrono(val startedMillis: Long = System.currentTimeMillis(), val clock: Clock = Clock.systemUTC()) {
    fun elapsedMillis(): Long = clock.millis() - startedMillis

    fun isWithin(duration: Duration): Boolean = elapsedMillis() <= duration.toMillis()
    fun hasTimedOut(duration: Duration): Boolean = !isWithin(duration)
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy