Removing Timer and adding isOverdue method on Deadline

This commit is contained in:
Viktor Klang 2012-02-01 12:04:42 +01:00
parent a61901adea
commit d4a1b38cdf
2 changed files with 5 additions and 36 deletions

View file

@ -4,7 +4,7 @@
package akka.actor
import akka.util.{ ByteString, Duration, Timer }
import akka.util.{ ByteString, Duration, Deadline }
import akka.util.duration._
import scala.util.continuations._
import akka.testkit._
@ -244,13 +244,13 @@ class IOActorSpec extends AkkaSpec with DefaultTimeout {
val promise = Promise[T]()(executor)
val timer = timeout match {
case Some(duration) Some(Timer(duration))
val timer: Option[Deadline] = timeout match {
case Some(duration) Some(Deadline(duration))
case None None
}
def check(n: Int, e: Throwable): Boolean =
(count.isEmpty || (n < count.get)) && (timer.isEmpty || timer.get.isTicking) && (filter.isEmpty || filter.get(e))
(count.isEmpty || (n < count.get)) && (timer.isEmpty || !timer.get.isOverdue()) && (filter.isEmpty || filter.get(e))
def run(n: Int) {
future onComplete {

View file

@ -10,43 +10,12 @@ import java.lang.{ Double ⇒ JDouble }
class TimerException(message: String) extends RuntimeException(message)
/**
* Simple timer class.
* Usage:
* <pre>
* import akka.util.duration._
* import akka.util.Timer
*
* val timer = Timer(30 seconds)
* while (timer.isTicking) { ... }
* </pre>
*/
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 (!(timeout.toNanos > (System.nanoTime - startTime.toNanos))) {
if (throwExceptionOnTimeout) throw new TimerException("Time out after " + timeout)
else false
} else true
}
}
case class Deadline(time: Duration) {
def +(other: Duration): Deadline = copy(time = time + other)
def -(other: Duration): Deadline = copy(time = time - other)
def -(other: Deadline): Duration = time - other.time
def timeLeft: Duration = this - Deadline.now
def isOverdue(): Boolean = timeLeft < Duration.Zero
}
object Deadline {
def now: Deadline = Deadline(Duration(System.nanoTime, NANOSECONDS))