This class stores a deadline, as obtained via Deadline.now
or the duration DSL:
import scala.concurrent.duration._ 3.seconds.fromNow
Its main purpose is to manage repeated attempts to achieve something (like awaiting a condition) by offering the methods hasTimeLeft
and timeLeft
. All durations are measured according to System.nanoTime
; this does not take into account changes to the system clock (such as leap seconds).
This class is not meant as a general purpose representation of time, it is optimized for the needs of scala.concurrent
.
Examples:
import scala.concurrent.duration._ val duration = Duration(100, MILLISECONDS) val duration = Duration(100, "millis") duration.toNanos duration < 1.second duration <= Duration.Inf
Invoking inexpressible conversions (like calling toSeconds
on an infinite duration) will throw an IllegalArgumentException.
Implicits are also provided for Int, Long and Double. Example usage:
import scala.concurrent.duration._ val duration = 100.millis
The DSL provided by the implicit conversions always allows construction of finite durations, even for infinite Double inputs; use Duration.Inf instead.
Extractors, parsing and arithmetic are also included:
val d = Duration("1.2 µs") val Duration(length, unit) = 5 millis val d2 = d * 2.5 val d3 = d2 + 1.millisecond
Calculations performed on finite durations always retain the more precise unit of either operand, no matter whether a coarser unit would be able to exactly express the same duration. This means that Duration can be used as a lossless container for a (length, unit) pair if it is constructed using the corresponding methods and no arithmetic is performed on it; adding/subtracting durations should in that case be done with care.
The semantics of arithmetic operations on Duration are two-fold:
java.lang.Double
when it comes to infinite or undefined valuesThe conversion between Duration and Double is done using Duration.toUnit (with unit NANOSECONDS) and Duration.fromNanos(Double)
The default ordering is consistent with the ordering of Double numbers, which means that Undefined is considered greater than all other durations, including Duration.Inf.
This class represents a finite duration. Its addition and subtraction operators are overloaded to retain this guarantee statically. The range of this class is limited to +-(2^63-1)
ns, which is roughly 292 years.
This object can be used as closing token for declaring a deadline at some future point in time:
import scala.concurrent.duration._ val deadline = 3 seconds fromNow
This object can be used as closing token if you prefer dot-less style but do not want to enable language.postfixOps:
import scala.concurrent.duration._ val duration = 2 seconds span
© 2002-2019 EPFL, with contributions from Lightbend.
Licensed under the Apache License, Version 2.0.
https://www.scala-lang.org/api/2.13.0/scala/concurrent/duration/index.html