Schedule
Schedule[-Env, -In, +Out] is a composable, time-aware state machine that describes when and how often a ZIO effect should execute. It observes an input In at each step β the effect's success value when repeating, or its error value when retrying β produces an output Out, and may require an environment Env for effects embedded in the schedule itself.
| Type parameter | Variance | Role |
|---|---|---|
Env | - (contravariant) | ZIO environment the schedule's own effects require |
In | - (contravariant) | Value the schedule observes at each step β the effect's success type when repeating, or its error type when retrying |
Out | + (covariant) | Value the schedule produces at each step β often a count, a Duration, or a transformed input |
Every concrete Schedule specifies three abstract members; all mutable data lives in the abstract State type:
trait Schedule[-Env, -In, +Out] extends Serializable { self =>
type State
def initial: State
def step(now: OffsetDateTime, in: In, state: State)(implicit
trace: Trace
): ZIO[Env, Nothing, (State, Out, Decision)]
}
step receives the current wall-clock OffsetDateTime, the current input, and the current state, and returns a ZIO that resolves to a triple: the updated state, the current output, and a Decision. A Decision.Continue(interval) tells the runtime how long to sleep before the next step; Decision.Done stops the loop.
Four design properties make Schedule a full algebra:
- State machine β All mutable data is captured in the abstract type member
State. Combinators pair twoStatetypes into a product, so composed schedules remain pure values with no hidden mutation. - Time-aware β
stepreceives the currentOffsetDateTimeand returns timing information viaIntervals, giving the runtime precise control over when each recurrence should begin. - Effect-capable β Because
stepreturnsZIO[Env, Nothing, ...], a schedule can read clocks, draw random numbers, or call any service, all without breaking the functional model. - Composable algebra β Operators such as
&&,||,>>>, and++build newSchedulevalues from existing ones, intersecting or unioning timing and combining outputs with full type-safety.
Motivationβ
Before diving into how to use Schedule, it's worth understanding why it's built the way it is β why step takes the three arguments it does, why Decision carries an Intervals instead of a plain Duration, and why State exists as an abstract type member instead of a type parameter. None of this is required to use Schedule effectively, but it turns the trait shown above from something that looks arbitrary into something that couldn't really be built any other way.
The Problemβ
Retrying and repeating effects sounds simple until the requirements pile up. A retry policy needs to remember how many attempts it's made so far, or how much time has elapsed β some kind of memory that survives from one attempt to the next. It needs to react to what actually happened β a RuntimeException might deserve a retry, a validation error might not, and a schedule that only ever counts attempts can't tell them apart. It needs to control timing precisely β not just "yes, try again" but when, since a real backoff strategy waits 100ms, then 200ms, then 400ms, not "immediately, forever." And critically, it needs to compose β a real system wants "retry with exponential backoff, but give up after a minute no matter what," which is two independent policies combined into one, not one policy hand-coded to do both jobs at once.
Hand-rolling this with recursion and ZIO.sleep calls solves it once, for one call site, with the logic buried inside a flatMap chain that can't be reused, tested without waiting in real time, or combined with a second policy. The problem Schedule solves is turning "when and how often should this run again" into a value β something you can build once, combine with &&/||/***, hand to ZIO#repeat or ZIO#retry, and test by simulating time instead of waiting for it.
The Idea, in Plain Englishβ
A Schedule is a tiny decision-maker that gets asked, over and over, one question: "given what just happened, and what you remember from before, should we go again β and if so, when β or should we stop?" Answering that question honestly requires exactly three things: somewhere to keep memory between one ask and the next, awareness of what just happened so the answer can depend on it, and a way to report back both a verdict (continue or stop) and, when continuing, precisely when. Everything in the real Schedule trait exists to make that one question answerable.
Building Up to the Real Modelβ
Rather than presenting the final trait and asking you to take its shape on faith, here's the same design arrived at the way it would actually be discovered β starting from the simplest thing that could possibly work, and adding exactly one capability at a time, each one motivated by something the previous version couldn't do.
Step 1: Just a Countβ
The simplest possible "keep retrying" rule counts attempts and stops at a limit:
def shouldContinue(attempt: Long): Boolean = attempt < 5
This is enough to answer "have we tried too many times yet?" β nothing more. There's no way to add a delay between attempts (Schedule.spaced, Schedule.exponential are impossible), and no way to look at what happened on a given attempt (Schedule.recurWhile, Schedule.recurUntil are impossible) β attempt is the only information available, and it says nothing about success or failure.
Step 2: Add Timingβ
Real backoff strategies don't just decide whether to continue β they decide when. Swap the Boolean for something that can also carry a delay:
def nextStep(attempt: Long): Option[Duration] =
if (attempt >= 5) None // stop
else Some((100 * attempt).millis) // continue, after this delay
None means stop; Some(delay) means continue after waiting delay. This is enough to express Schedule.spaced, Schedule.linear, and Schedule.exponential β real timing strategies, not just a raw count. It's still blind to the actual effect: two different errors on two different attempts get treated identically, because attempt is still the only input.
Step 3: Generalize the Counter into State, and Add Inputβ
The counter in Step 2 is really just one specific kind of memory. A schedule might instead need to remember the last delay used, a running total of elapsed time, or nothing at all β any of these should be expressible, not just a Long. At the same time, the schedule needs to see what actually happened at each step β the error being retried, or the value being repeated β not just how many times it's been asked:
trait MiniSchedule[State, In] {
def initial: State
def step(state: State, in: In): (State, Option[Duration])
}
Generalizing the counter into an abstract State unlocks any policy that needs to remember something other than a count β the previous delay, an accumulated Chunk of outputs, an elapsed Duration. Adding In unlocks reacting to content β Schedule.recurWhile, Schedule.recurUntil, and the whole "conditional" family become expressible, because the step function can finally inspect what happened, not just count how many times it's been called.
Step 4: Report Something Backβ
ZIO#repeat's whole point is often to hand back something useful when it finishes β the number of times it ran, the last value produced, an accumulated log. Step 3's model can decide when to stop, but it has nothing to report:
trait MiniSchedule[State, In, Out] {
def initial: State
def step(state: State, in: In): (State, Out, Option[Duration])
}
Adding Out is what makes ZIO#repeat's return value meaningful, and it's what every output-facing combinator β Schedule#map, Schedule#tapOutput, Schedule#collectAll β actually operates on. Without it, a schedule can gate whether something continues, but can never itself produce a value the caller cares about.
Step 5: Make It Effectful, and Make Time Explicitβ
Some schedules need to do more than pure computation to decide their next step β Schedule#jittered needs randomness, Schedule.secondOfMinute and the other calendar schedules need to know the current wall-clock time to compute the next matching boundary, and a schedule built from Schedule.recurWhileZIO needs to run a real effect to evaluate its condition. Deciding the next step has to become an effect, and the current time has to become an explicit input rather than something each schedule reads for itself:
trait MiniSchedule[Env, State, In, Out] {
def initial: State
def step(now: OffsetDateTime, in: In, state: State): ZIO[Env, Nothing, (State, Out, Option[Duration])]
}
now is passed in rather than read via Clock.currentDateTime inside each schedule for a specific reason: when two schedules are combined with &&, both sides have to be evaluated against the same instant for their timing decisions to be comparable at all β if each side read the clock independently, a few nanoseconds apart, &&'s "intersect the two windows" logic would be comparing intervals computed against two different "nows." Threading now through the call, rather than letting each schedule fetch it independently, is what makes the two sides of a combined schedule comparable in the first place.
Step 6: Refine "a Delay" into "a Set of Valid Windows"β
Option[Duration] says "wait exactly this long" β but combining two schedules needs more than that. && has to compute the intersection of two schedules' acceptable next-run windows, and || the union; neither operation is well-defined on a single point-in-time delay. Two schedules due at 1s and 5s don't "intersect" to a delay at all unless you think in terms of windows β the earliest and latest moment each schedule considers acceptable β rather than a single instant. And a schedule can have more than one acceptable window at once (a calendar schedule can validly fire at several boundaries): a bare Duration, or even a single window, can't represent that either. This is exactly why the real model represents a step's continue-instruction with a whole set of time windows β Interval for one window (with real intersect/union/comparison operations), Intervals for a sorted, non-overlapping collection of them β bundled into a Decision that also has to allow for the "no more windows, we're done" case:
sealed trait Decision
object Decision {
final case class Continue(interval: Intervals) extends Decision
case object Done extends Decision
}
This is precisely the Decision, Interval, and Intervals machinery documented in Nested Types β not designed for its own sake, but because "intersect two schedules' timing" and "union two schedules' timing" are real operations && and || need to perform, and neither is expressible over a bare Duration.
The Real Modelβ
Assembling Steps 3 through 6 β state, input, output, effectfulness, explicit time, and windows-instead-of-a-single-delay β produces exactly the trait shown at the top of this page:
trait Schedule[-Env, -In, +Out] extends Serializable { self =>
type State
def initial: State
def step(now: OffsetDateTime, in: In, state: State)(implicit
trace: Trace
): ZIO[Env, Nothing, (State, Out, Decision)]
}
State is an abstract type member rather than a type parameter for a practical reason: when two schedules combine (&&, ***, andThen, β¦), their combined state is a pair of the two originals' states β (self.State, that.State) β and that pair's shape is different for every combination. Making State a member lets each combinator declare its own concrete state shape via WithState without polluting Schedule's own type parameter list with a fourth, ever-changing parameter.
Everything documented in Core Operations is a function that builds a new step out of one or two existing ones β Schedule#map runs self.step and transforms the Out in the result; && runs both sides' step against the same now and combines their decisions by intersecting their Intervals; Schedule.recurs is a step that ignores its State after decrementing a counter. There's no separate execution engine hidden elsewhere β ZIO#repeat, ZIO#retry, ZIO#schedule, and manual driving are all callers that do the same thing: run the effect (or not, for ZIO#schedule), call step, and either sleep until the returned Intervals and call it again, or stop on Decision.Done. Once step is understood, so is the entire type.
Usageβ
A typical use is retrying a failing effect with exponential backoff capped to a fixed number of attempts, combined with repeat for periodic polling:
import zio._
// Retry with exponential backoff, at most 5 additional attempts, with random jitter
val policy: Schedule[Any, Any, Long] =
Schedule.recurs(5) <* Schedule.exponential(100.millis).jittered
// policy: Schedule[Any, Any, Long] = zio.Schedule$$anon$13@498524bc
// Retry an HTTP call up to 5 times, waiting 100ms, 200ms, 400ms β¦ between attempts
val result: ZIO[Any, Nothing, String] =
ZIO.fail(new RuntimeException("service unavailable"))
.retry(policy)
.orElse(ZIO.succeed("fallback"))
// result: ZIO[Any, Nothing, String] = FoldZIO(
// trace = "repl.MdocSession.MdocApp0.result(schedule.md:21)",
// first = FlatMap(
// trace = "repl.MdocSession.MdocApp0.result(schedule.md:20)",
// first = Sync(
// trace = "",
// eval = zio.ZIO$$$Lambda$18892/0x0000781692da9d08@52cb9877
// ),
// successK = zio.ZIO$$$Lambda$19656/0x0000781692f53518@509e8736
// ),
// successK = zio.ZIO$$$Lambda$18895/0x0000781692dabf80@2520512d,
// failureK = zio.ZIO$$Lambda$20448/0x0000781693105478@5dd50350
// )
// The same schedule type drives repeat for polling or heartbeat loops:
val heartbeat: ZIO[Any, Nothing, Long] =
ZIO.logInfo("ping").repeat(Schedule.spaced(5.seconds))
// heartbeat: ZIO[Any, Nothing, Long] = Mapped(
// trace = "repl.MdocSession.MdocApp0.heartbeat(schedule.md:25)",
// first = FlatMap(
// trace = "repl.MdocSession.MdocApp0.heartbeat(schedule.md:25)",
// first = Sync(
// trace = "",
// eval = zio.ZIO$$$Lambda$18892/0x0000781692da9d08@52cb9877
// ),
// successK = zio.ZIO$$$Lambda$19656/0x0000781692f53518@2c93fb35
// ),
// successK = zio.ZIO$$Lambda$20678/0x00007816931e85a8@1af4c7fb
// )
Installationβ
Schedule is part of the core zio module; no additional dependency is needed:
libraryDependencies += "dev.zio" %% "zio" % "2.1.27"
Creating Valuesβ
The companion object provides a large set of pre-built schedules. Every factory returns a WithState[S, Env, In, Out], making the concrete state type S visible to the type system.
Predefined Schedulesβ
Three val members provide always-recurring base schedules that serve as building blocks for more complex policies:
object Schedule {
val forever: Schedule.WithState[Long, Any, Any, Long]
val count: Schedule.WithState[Long, Any, Any, Long]
val elapsed: Schedule.WithState[Option[OffsetDateTime], Any, Any, Duration]
}
Schedule.forever and Schedule.count are equivalent β both always recur, outputting an increasing count starting at 0. Schedule.elapsed always recurs and outputs the Duration since the very first step.
We can pipe Schedule.elapsed after a delay schedule to observe how much wall-clock time has passed:
import zio._
// Produce delay durations, then observe total elapsed time
val tickAndMeasure: Schedule[Any, Any, Duration] =
Schedule.spaced(500.millis) >>> Schedule.elapsed
Fixed-Count Recurrenceβ
These factories build schedules that stop after a fixed number of repetitions:
object Schedule {
def recurs(n: Long): Schedule.WithState[Long, Any, Any, Long]
def recurs(n: Int): Schedule.WithState[Long, Any, Any, Long]
def once: Schedule.WithState[Long, Any, Any, Unit]
def stop: Schedule.WithState[Long, Any, Any, Unit]
}
Schedule.recurs(n) runs n additional times after the first execution, outputting the counts 0 through n β 1. Both the Long and Int overloads behave identically; negative values behave as 0. Schedule.once is recurs(1).unit β one additional run. Schedule.stop is recurs(0).unit β no additional runs.
import zio._
val fiveRetries = Schedule.recurs(5) // 5 additional runs, outputs: 0, 1, 2, 3, 4
val singleRetry = Schedule.once // 1 additional run
val noRetry = Schedule.stop // 0 additional runs
Delay-Based Recurrenceβ
These factories build always-recurring schedules whose primary purpose is to control the delay between steps:
object Schedule {
def spaced(duration: Duration):
Schedule.WithState[Long, Any, Any, Long]
def fixed(interval: Duration):
Schedule.WithState[(Option[(Long, Long)], Long), Any, Any, Long]
def windowed(interval: Duration):
Schedule.WithState[(Option[Long], Long), Any, Any, Long]
def linear(base: Duration):
Schedule.WithState[Long, Any, Any, Duration]
def exponential(base: Duration, factor: Double = 2.0):
Schedule.WithState[Long, Any, Any, Duration]
def fibonacci(one: Duration):
Schedule.WithState[(Duration, Duration), Any, Any, Duration]
}
Each of these controls timing in a different way:
spaced(d)β the simplest one. After each run finishes, wait exactlyd, then run again. If the effect itself is slow, the gap after it is still alwaysd.fixed(d)β instead of timing from when the run finishes, this times from when it started, aiming for one run everyd. If a run happens to take longer thand, the next one fires immediately afterward (it never fires twice at once to "catch up").windowed(d)β divides time intod-long slices starting from whenever the schedule is first stepped, and fires once per slice at that slice's boundary β the alignment is relative to the schedule's own start time, not to absolute wall-clock marks like:00/:10/:20. This runs once per slice, no matter when inside the previous slice it actually started.linear(base)β each delay grows by one morebasethan the last:base,2Γbase,3Γbase, and so on. Useful when you want retries to slow down gradually.exponential(base, factor)β each delay is multiplied byfactor(default2.0), so it grows fast:base,baseΓ2,baseΓ4,baseΓ8, β¦ This is the classic "exponential backoff" used when retrying a failing remote call, so you back off quickly instead of hammering it.fibonacci(one)β delays follow the Fibonacci sequence (each one is the sum of the two before it):one, one, 2Γone, 3Γone, 5Γone, β¦. A middle ground betweenSchedule.linear's steady growth andSchedule.exponential's fast growth.
Recall from Usage that a Schedule[-Env, -In, +Out] produces an Out value on every step β that third type parameter. For spaced, fixed, and windowed, Out is just a Long counter (how many times the schedule has fired so far), which isn't very interesting on its own. But linear, exponential, and fibonacci set Out to the actual Duration they just waited. In other words, the delay isn't hidden inside the schedule β it is the schedule's output, exactly like any other Out value. That means any combinator that works on a schedule's output also works here, for free β including tapOutput (covered later, in Tapping Inputs and Outputs), which runs an effect on every Out value without changing what the schedule does. Here it's used to log each backoff delay right before it's used:
import zio._
// `tapOutput` receives each Duration the schedule produces β here, we just log it
val loggedBackoff: Schedule[Any, Any, Duration] =
Schedule.exponential(100.millis).tapOutput(delay => ZIO.logInfo(s"retrying in $delay"))
val result: ZIO[Any, Nothing, String] =
ZIO.fail(new RuntimeException("service unavailable"))
.retry(loggedBackoff)
.orElse(ZIO.succeed("gave up after all attempts"))
Running result logs retrying in 100ms, then retrying in 200ms, then retrying in 400ms, β¦ right before each retry β the exact Duration values Schedule.exponential is producing as its Out, read straight off the schedule with no separate tracking of your own.
The following block shows these schedules as candidates for retry policies with progressively longer backoffs:
import zio._
val linear100ms = Schedule.linear(100.millis) // 100ms, 200ms, 300ms, ...
val doubling100ms = Schedule.exponential(100.millis) // 100ms, 200ms, 400ms, ...
val tripling100ms = Schedule.exponential(100.millis, 3.0) // 100ms, 300ms, 900ms, ...
val fibonacci100ms = Schedule.fibonacci(100.millis) // 100ms, 100ms, 200ms, 300ms, ...
val every5s = Schedule.fixed(5.seconds)
val windowOf10s = Schedule.windowed(10.seconds)
Duration-Boundedβ
These factories build schedules that recur for a specific total duration:
object Schedule {
def duration(duration: Duration):
Schedule.WithState[Boolean, Any, Any, Duration]
def fromDuration(duration: Duration):
Schedule.WithState[Boolean, Any, Any, Duration]
def fromDurations(duration: Duration, durations: Duration*):
Schedule.WithState[(::[Duration], Boolean), Any, Any, Duration]
def upTo(duration: Duration):
Schedule.WithState[Option[OffsetDateTime], Any, Any, Duration]
}
duration(d) and fromDuration(d) are aliases: both recur exactly once after sleeping d, then stop. fromDurations(d, ds*) recurs once for each provided duration, sleeping the corresponding duration between steps. upTo(totalDuration) recurs continuously while total elapsed time is less than totalDuration, outputting the elapsed Duration.
import zio._
// Recur once after 5 seconds
val onceAfter5s = Schedule.duration(5.seconds)
// Four recurrences, each delayed from the previous one by 4s, then 7s, then 12s, then 19s (firing at +4s, +11s, +23s, +42s)
val customSteps = Schedule.fromDurations(4.seconds, 7.seconds, 12.seconds, 19.seconds)
// Repeat for at most 30 seconds, outputting elapsed time
val thirtySeconds = Schedule.upTo(30.seconds)
Schedule.upTo is easy to misread as "recur every 30 seconds" β it isn't. On its own it adds no delay at all: it just keeps recurring as fast as possible, tracking how much total time has passed, and stops once that exceeds 30.seconds. Used by itself with ZIO#repeat, thirtySeconds would fire thousands of times in that window, back to back. Schedule.upTo becomes useful once you intersect it (&&) with a schedule that does provide a delay, capping that schedule's total run time without changing how often it fires in between:
import zio._
// Poll once a second, but give up after 30 seconds total β not "wait 30s, then poll once"
val pollFor30Seconds: Schedule[Any, Any, (Long, Duration)] =
Schedule.spaced(1.second) && Schedule.upTo(30.seconds)
val poll: ZIO[Any, Nothing, Unit] =
ZIO.logInfo("checking status").repeat(pollFor30Seconds).unit
Here Schedule.spaced(1.second) decides the rhythm (once per second) and Schedule.upTo(30.seconds) decides the deadline (stop after 30 seconds have passed); && keeps both running together and stops as soon as either one would stop β see Intersection (AND) for how && combines two schedules.
Calendar and Cron-Likeβ
The calendar schedules trigger at specific positions within a time unit, similar to cron expressions:
object Schedule {
def secondOfMinute(second0: Int):
Schedule.WithState[(OffsetDateTime, Long), Any, Any, Long]
def minuteOfHour(minute: Int):
Schedule.WithState[(OffsetDateTime, Long), Any, Any, Long]
def hourOfDay(hour: Int):
Schedule.WithState[(OffsetDateTime, Long), Any, Any, Long]
def dayOfWeek(day: Int):
Schedule.WithState[(OffsetDateTime, Long), Any, Any, Long]
def dayOfMonth(day: Int):
Schedule.WithState[(OffsetDateTime, Long), Any, Any, Long]
}
Each one picks a fixed position inside a repeating unit of time, and fires every time the clock reaches that position:
secondOfMinute(s)β fires at seconds(0β59) of every minute.secondOfMinute(30)fires at12:00:30,12:01:30,12:02:30, and so on.minuteOfHour(m)β fires at minutem(0β59) of every hour.minuteOfHour(0)fires once at the top of every hour.hourOfDay(h)β fires at hourh(0β23) of every day.hourOfDay(9)fires once at 09:00 each day.dayOfWeek(d)β fires at midnight on ISO-8601 weekdayd(1 = Monday, β¦, 7 = Sunday).dayOfWeek(2)fires at midnight every Tuesday.dayOfMonth(d)β fires at midnight on dayd(1β31) of every month. When the schedule steps on or after daydwithin the current month, it advances to the next month that actually has dayd, skipping months that don't (e.g. day31skips February). But when it steps on a day earlier in the month thand, it jumps straight to daydin the current month instead β see the caution below.
Each one outputs how many times it has fired so far, as a Long starting at 0 β the same shape as Schedule.forever, just triggered on a calendar position instead of a fixed cadence.
import zio._
val everyMinuteAt30 = Schedule.secondOfMinute(30) // every minute at :30
val everyHourOnHour = Schedule.minuteOfHour(0) // every hour at :00
val daily9am = Schedule.hourOfDay(9) // daily at 09:00
val everyTuesday = Schedule.dayOfWeek(2) // every Tuesday
val firstOfMonth = Schedule.dayOfMonth(1) // first day of each month
Calendar schedules validate their argument lazily. A call such as Schedule.dayOfWeek(9) compiles without error, but the schedule dies with IllegalArgumentException the first time it runs. Valid ranges: Schedule.secondOfMinute 0β59, Schedule.minuteOfHour 0β59, Schedule.hourOfDay 0β23, Schedule.dayOfWeek 1β7 (ISO-8601), Schedule.dayOfMonth 1β31.
Separately, Schedule.dayOfMonth's "skip a month without this day" behavior only works when the schedule is stepped on or after the target day-of-month within the current month. Stepping on a day earlier in the month than the target β in a month that doesn't have that day β currently throws java.time.DateTimeException rather than skipping to the next valid month. For example, stepping Schedule.dayOfMonth(31) on essentially any day before the 31st in February, April, June, September, or November crashes with Invalid date '<MONTH> 31' instead of advancing to the next month that has a 31st.
Conditional (Input-Driven)β
These factories produce schedules whose recurrence is controlled by inspecting each input value.
Predicate and Equality Variantsβ
Schedule.recurWhile, Schedule.recurWhileZIO, and Schedule.recurWhileEquals recur as long as a condition holds; Schedule.recurUntil, Schedule.recurUntilZIO, and Schedule.recurUntilEquals recur until a condition holds. All pass the input through as output with no delay.
The While family (note: Schedule.recurWhileZIO has no implicit Trace parameter):
object Schedule {
def recurWhile[A](f: A => Boolean):
Schedule.WithState[Unit, Any, A, A]