From 6cb887e1a58f1fcfb21dcd02bb950eab7fff4ba3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Bone=CC=81r?= Date: Tue, 24 Jan 2012 12:00:53 +0100 Subject: [PATCH] Changed akka.util.Timer to use nanos and added a 'timeLeft' method. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jonas Bonér --- .../src/main/scala/akka/util/Duration.scala | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/akka-actor/src/main/scala/akka/util/Duration.scala b/akka-actor/src/main/scala/akka/util/Duration.scala index 65d6e6148c..312d733904 100644 --- a/akka-actor/src/main/scala/akka/util/Duration.scala +++ b/akka-actor/src/main/scala/akka/util/Duration.scala @@ -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) { ... } * */ -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 }