Skip to content

Kotlin

The bikesched-kotlin module adds Kotlin extensions on top of the Java API, in the package org.bikesched.kotlin; it depends on bikesched-core and the Kotlin standard library only.

// bikesched-jackson with Jackson's Kotlin module (tools.jackson.module:jackson-module-kotlin)
val kotlinObjectMapper = JsonMapper.builder().addModule(KotlinModule.Builder().build()).build()

val bikesched = bikesched(ds) {                     // instead of Bikesched.builder(ds)…build()
    jsonMapper = JacksonJsonMapper(kotlinObjectMapper)
    defaultJobTimeout = 5.minutes                   // kotlin.time.Duration everywhere
}

data class Order(val id: String, val amount: Int)

bikesched.handleJobs<Order>("order") { order ->    // this: Job, order: the mapped payload
    val reservation = step<Reservation>("reserve-payment", compensation = { _, r -> payments.release(r) }) {
        payments.reserve(order)
    }
    val payment = waitForEvent<Payment>(step = "await-payment", name = "payment-received", key = order.id)
    val shipment = step<Shipment>("ship") { shipping.ship(order, reservation, payment) }
    publishEvent(name = "order-shipped", key = order.id, payload = shipment)
}

bikesched.createJob(name = "order", payload = Order("o-1", 100))
bikesched.publishEvent(name = "payment-received", key = "o-1", payload = payment)
bikesched.createRecurringJob(name = "cleanup", recurrence = every(1.hours)) { cleanup.run() }

Functions

createJob, createRecurringJob, publishEvent, waitForEvent and startJob take named arguments. Only the job name (resp. step, event name and key) and the recurrence are required; omitted options keep the builder defaults:

Function Arguments
handleJobs<T>(name) { payload -> }, handleJobs(name) { } registers the handler; the Job is the receiver
handleJobFailures<T>(name) { payload -> }, handleJobFailures(name) { } registers the failure handler; the FailedJob is the receiver
createJob(name, payload, at, delay, priority, maxAttempts, timeout, connection, idempotencyKey, reference, actor, onFailure) { … } schedules a job (at or delay, otherwise due now; connection joins the caller’s transaction) and returns its id; with an idempotencyKey, the id of the existing job with the key; reference is the job’s reference, actor the user named in its history
createJob(typedJob, payload, at, delay, priority, maxAttempts, timeout, connection, idempotencyKey, reference, actor, onFailure) { … } the same for a TypedJob<T>: the payload has the typed job’s payload class, the optional handlers get it as T
createRecurringJob(name, recurrence, payload, firstRun, delay, priority, maxAttempts, timeout, reference, actor, onFailure) { … } registers a recurring job and returns the id of its pending occurrence
Bikesched.publishEvent(name, key, payload, retention, connection, idempotencyKey, reference, actor) publishes an event and returns its id; with an idempotencyKey, the id of the earlier event with the key while it is kept; reference is the event’s reference, actor the user named in its history
Job.publishEvent(name, key, payload, retention, stepName, reference) publishes once as a durable job step and returns the event’s id, the same on every run; the event has the job’s reference unless reference is given
waitForEvent<T>(step, name, key, timeout, onFailure) (in a handler) waits for an event and returns its payload; once the timeout (or the default event timeout) passes, the job fails, unless onFailure = { failing -> … } resolves the wait with a fallback (e.g. waitForEvent<Payment?>(…, timeout = 3.days, onFailure = { it.resolve(null) }))
step<T>(name, compensation, retryBackoff, onFailure) { … } (in a handler) runs a durable step; the optional compensation = { step, result -> … } undoes it if the job is cancelled or fails permanently; onFailure = { failing -> … } handles its failure in the job’s last attempt and may failing.resolve(x) it with a fallback
startJob(name, payload, stepName, at, delay, priority, maxAttempts, timeout, reference, compensation) (in a handler) starts a child job once as a durable step and returns its id, the same on every run; it has the parent’s reference unless reference is given; the optional compensation = { step, childId -> … } e.g. cancels it
poll<T>(name, interval, timeout, onFailure) { step -> … } (in a handler) polls until the trailing handler returns Poll.ready(value), checking every interval (a Duration or a RetryBackoff); once the optional timeout passes, the job fails with a PollTimeoutException, unless onFailure = { failing -> … } resolves the poll (it also handles a check failing in the last attempt); a poll<Unit> stores no value
awaitJob<T>(childJobId, timeout) (in a handler) waits for a child job and returns its JobResult<T>; JobResult.TimedOut once the optional timeout passed

The optional trailing handler of createJob and createRecurringJob is registered for the name unless it already has one; with a payload it gets the payload as its type, otherwise only the Job. onFailure = { payload -> … } (with the FailedJob as receiver) registers the name’s failure handler the same way.

Helpers for the Java API

Helper Instead of
bikesched(dataSource) { … } Bikesched.builder(dataSource)…build()
job.payload<T>() payload(T.class)
schedule(Duration), timeout(Duration), retryAfter(Duration), updateTimeout(Duration), postpone(Duration), sleep(String, Duration), every(Duration), everyAfterEnd(Duration), fixedBackoff, exponentialBackoff java.time.Duration arguments
findJobOrNull(id) Optional

Nullability

The Java API is annotated with JSpecify, so Kotlin sees its nullability instead of platform types: job.payload() is String?, and a Java callback interface implemented in Kotlin gets values that may be null as nullable types, e.g. the payload of a TypedJobHandler<Order> lambda is Order?.

Reified helpers check nullability: payload<Order>() throws for a job without payload, payload<Order?>() returns null. Likewise, a handleJobs<Order> handler is not called for a job without payload (the attempt fails with an IllegalStateException), a handleJobs<Order?> handler gets null.