2012-04-25 18:34:16 +02:00
|
|
|
package akka.pattern
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
|
|
|
|
|
*/
|
|
|
|
|
|
2012-06-29 13:33:20 +02:00
|
|
|
import scala.concurrent.util.Duration
|
2012-07-04 15:25:30 +02:00
|
|
|
import scala.concurrent.{ ExecutionContext, Promise, Future }
|
2012-04-25 18:34:16 +02:00
|
|
|
import akka.actor._
|
2012-07-22 14:16:09 +02:00
|
|
|
import akka.util.NonFatal
|
2012-04-25 18:34:16 +02:00
|
|
|
|
|
|
|
|
trait FutureTimeoutSupport {
|
|
|
|
|
/**
|
2012-07-04 15:25:30 +02:00
|
|
|
* Returns a [[scala.concurrent.Future]] that will be completed with the success or failure of the provided value
|
2012-04-25 18:34:16 +02:00
|
|
|
* after the specified duration.
|
|
|
|
|
*/
|
|
|
|
|
def after[T](duration: Duration, using: Scheduler)(value: ⇒ Future[T])(implicit ec: ExecutionContext): Future[T] =
|
|
|
|
|
if (duration.isFinite() && duration.length < 1) value else {
|
|
|
|
|
val p = Promise[T]()
|
2012-07-22 14:16:09 +02:00
|
|
|
val c = using.scheduleOnce(duration) {
|
|
|
|
|
p completeWith { try value catch { case NonFatal(t) ⇒ Future.failed(t) } }
|
|
|
|
|
}
|
2012-07-04 15:25:30 +02:00
|
|
|
val f = p.future
|
|
|
|
|
f onComplete { _ ⇒ c.cancel() }
|
|
|
|
|
f
|
2012-04-25 18:34:16 +02:00
|
|
|
}
|
|
|
|
|
}
|