Added Timer class to be used in testing and more.
Signed-off-by: Jonas Bonér <jonas@jonasboner.com>
This commit is contained in:
parent
5eeda5bf40
commit
aeb8178007
1 changed files with 29 additions and 0 deletions
|
|
@ -8,6 +8,35 @@ import java.util.concurrent.TimeUnit
|
|||
import TimeUnit._
|
||||
import java.lang.{ Long ⇒ JLong, 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(duration: Duration, throwExceptionOnTimeout: Boolean = false) {
|
||||
val startTimeInMillis = System.currentTimeMillis
|
||||
val timeoutInMillis = duration.toMillis
|
||||
|
||||
/**
|
||||
* 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)
|
||||
else false
|
||||
} else true
|
||||
}
|
||||
}
|
||||
|
||||
object Duration {
|
||||
def apply(length: Long, unit: TimeUnit): Duration = new FiniteDuration(length, unit)
|
||||
def apply(length: Double, unit: TimeUnit): Duration = fromNanos(unit.toNanos(1) * length)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue