Changed akka.util.Timer to use nanos and added a 'timeLeft' method.
Signed-off-by: Jonas Bonér <jonas@jonasboner.com>
This commit is contained in:
parent
12d8b5bf4b
commit
6cb887e1a5
1 changed files with 11 additions and 6 deletions
|
|
@ -17,21 +17,26 @@ class TimerException(message: String) extends RuntimeException(message)
|
|||
* import akka.util.duration._
|
||||
* import akka.util.Timer
|
||||
*
|
||||
* val timer = Timer(30.seconds)
|
||||
* val timer = Timer(30 seconds)
|
||||
* while (timer.isTicking) { ... }
|
||||
* </pre>
|
||||
*/
|
||||
case class Timer(duration: Duration, throwExceptionOnTimeout: Boolean = false) {
|
||||
val startTimeInMillis = System.currentTimeMillis
|
||||
val timeoutInMillis = duration.toMillis
|
||||
case class Timer(timeout: Duration, throwExceptionOnTimeout: Boolean = false) {
|
||||
val startTime = Duration(System.nanoTime, NANOSECONDS)
|
||||
|
||||
def timeLeft: Duration = {
|
||||
val time = timeout.toNanos - (System.nanoTime - startTime.toNanos)
|
||||
if (time <= 0) Duration(0, NANOSECONDS)
|
||||
else Duration(time, NANOSECONDS)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true while the timer is ticking. After that it either throws and exception or
|
||||
* returns false. Depending on if the 'throwExceptionOnTimeout' argument is true or false.
|
||||
*/
|
||||
def isTicking: Boolean = {
|
||||
if (!(timeoutInMillis > (System.currentTimeMillis - startTimeInMillis))) {
|
||||
if (throwExceptionOnTimeout) throw new TimerException("Time out after " + duration)
|
||||
if (!(timeout.toNanos > (System.nanoTime - startTime.toNanos))) {
|
||||
if (throwExceptionOnTimeout) throw new TimerException("Time out after " + timeout)
|
||||
else false
|
||||
} else true
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue