Skip to content

Commit

Permalink
Added scheduler (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
sksamuel authored Jun 11, 2023
1 parent 51c47d6 commit 4b5735c
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions aedile-core/src/main/kotlin/com/sksamuel/aedile/core/caffeine.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ import com.github.benmanes.caffeine.cache.stats.StatsCounter
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.future.asCompletableFuture
import kotlinx.coroutines.launch
import kotlin.time.Duration
import kotlin.time.Duration.Companion.nanoseconds
import kotlin.time.toJavaDuration

data class Configuration<K, V>(
Expand Down Expand Up @@ -108,6 +110,8 @@ data class Configuration<K, V>(
* See full docs at [Caffeine.weigher].
*/
var weigher: ((K, V) -> Int)? = null,

var scheduler: Scheduler? = null,
)

/**
Expand Down Expand Up @@ -154,9 +158,22 @@ fun <K, V> caffeineBuilder(configure: Configuration<K, V>.() -> Unit = {}): Buil
if (c.weakKeys == true) caffeine.weakKeys()
if (c.softValues == true) caffeine.softValues()

c.scheduler?.let { scheduler ->
caffeine.scheduler { _, command, delay, unit ->
scheduler.schedule(
{ command.run() },
unit.toNanos(delay).nanoseconds,
).asCompletableFuture()
}
}

return Builder(scope, caffeine)
}

fun interface Scheduler {
fun schedule(command: () -> Unit, duration: Duration): Deferred<Unit>
}

class Builder<K, V>(
private val scope: CoroutineScope,
private val caffeine: Caffeine<Any, Any>,
Expand Down

0 comments on commit 4b5735c

Please sign in to comment.