Skip to main content
Version: 2.x

Duration

Every ZIO operator that waits, delays or times out takes a Duration: ZIO.sleep, ZIO#timeout, ZIO#delay, the Schedule constructors and the Clock service. Duration is a type alias for java.time.Duration, so every Java duration is a ZIO duration and no conversion is needed between the two. ZIO adds syntax to build durations from numbers, arithmetic that cannot overflow, comparison operators, and a short text rendering.

Creating Durationsโ€‹

The usual way to build a duration is the syntax on Int and Long values that import zio._ brings in:

import zio._

val timeout: Duration = 5.seconds
// timeout: Duration = PT5S
val poll: Duration = 250.millis
// poll: Duration = PT0.25S
val day: Duration = 1.day
// day: Duration = PT24H

Each unit has a plural name and short aliases: nanos (nanoseconds, nano), micros (microseconds, micro), millis (milliseconds, milli), seconds (second), minutes (minute), hours (hour) and days (day). A day is exactly 24 hours.

The Duration object has constructors for values that come from elsewhere:

ConstructorReturns
Duration(amount, unit)amount units of a TimeUnit or ChronoUnit
Duration.fromMillis(millis)A duration of millis milliseconds
Duration.fromNanos(nanos)A duration of nanos nanoseconds
Duration.fromSeconds(seconds)A duration of seconds seconds
Duration.fromInterval(start, end)The time between two Instants or two OffsetDateTimes
Duration.fromInstant(instant)The time from the Unix epoch to instant, in whole milliseconds
Duration.fromScala(duration)A Scala duration; Duration.Inf becomes Duration.Infinity
Duration.fromJava(duration)A Java duration clamped to the range from zero to Infinity
Duration.Finite(nanos)A duration of nanos nanoseconds, or zero when nanos is negative

Two constants complete the set: Duration.Zero and Duration.Infinity.

Infinityโ€‹

ZIO treats Duration.Infinity, which is Long.MaxValue nanoseconds (about 292 years), as "forever". ZIO.sleep(Duration.Infinity) never resumes, and arithmetic saturates at it instead of overflowing. Duration#fold picks one branch for Infinity and another for every finite duration, and the Duration.Finite extractor matches only the finite ones:

def describe(d: Duration): String =
d match {
case Duration.Finite(nanos) => s"$nanos ns"
case _ => "forever"
}

describe(2.seconds)
// res0: String = "2000000000 ns"
describe(Duration.Infinity)
// res1: String = "forever"

Duration.Infinity.fold("forever", d => d.render)
// res2: String = "forever"

Arithmetic and Comparisonโ€‹

Duration#+ and Duration#* count a negative operand as zero and stop at Duration.Infinity instead of overflowing. Duration#* takes a Double factor, which is how schedules scale delays:

1.second + 500.millis
// res3: Duration = PT1.5S

Duration.Infinity + 1.second
// res4: Duration = PT2562047H47M16.854775807S

2.seconds * 1.5
// res5: Duration = PT3S

<, <=, >, >= and == compare lengths, Duration#min and Duration#max pick the shorter or longer duration, and an implicit Ordering[Duration] lets us sort them:

2.seconds > 1500.millis
// res6: Boolean = true

List(3.seconds, 1.second, 2.seconds).sorted
// res7: List[Duration] = List(PT1S, PT2S, PT3S)

5.seconds.min(10.seconds)
// res8: Duration = PT5S

All the methods of java.time.Duration are available too, such as toMillis, getSeconds, plus and isZero.

Renderingโ€‹

Duration#render returns a short text that uses the largest units, which suits log messages. It keeps milliseconds only for durations under one minute, so 1.hour + 4.millis renders as 1 h:

90.seconds.render
// res9: String = "1 m 30 s"

(1.hour + 2.minutes + 3.seconds + 4.millis).render
// res10: String = "1 h 2 m 3 s"

Converting to Scala and Java Durationsโ€‹

To pass a duration to code that expects another type, Duration#asScala (also Duration#asFiniteDuration) returns a Scala FiniteDuration, and Duration#asJava returns the same value typed as java.time.Duration. In the other direction, Duration.fromScala and Duration.fromJava convert Scala and Java durations:

import scala.concurrent.duration.{Duration => ScalaDuration}

3.seconds.asScala
// res11: scala.concurrent.duration.Duration = 3000000000 nanoseconds

Duration.fromScala(ScalaDuration(2, "minutes"))
// res12: Duration = PT2M
Duration.fromScala(ScalaDuration.Inf)
// res13: Duration = PT2562047H47M16.854775807S

Durations in Configโ€‹

Config.duration reads a duration from configuration. It accepts ISO-8601 text such as PT5S and the Scala syntax 5 seconds; see Configuration for loading configs.

See Alsoโ€‹

  • Clock โ€” The service that sleeps for a Duration and reads the current time.
  • Schedule โ€” Recurrence policies whose delays are durations.

ZIO Chat

๐ŸŒŸ Greetings from ZIO Chat! ๐ŸŒŸ Have questions about ZIO? Look no further! I'm here to be your ZIO guru. Whether you're a seasoned pro or just starting out, I've got answers tailored just for you. Fire away with your ZIO queries, and I'll hit you back with the best insights I've got. Let's dive into the world of ZIO together!