Skip to content

@ericacm /FutureTimeoutSupport.scala
Last active

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
Future timeout support
import akka.util.{Duration, NonFatal}
import akka.dispatch.{Promise, ExecutionContext, Future}
// Copied from Akka 2.1-M1
trait FutureTimeoutSupport {
* Returns a [[akka.dispatch.Future]] that will be completed with the success or failure of the provided value
* 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) {
try value catch { case NonFatal(t) Promise.failed(t).future }
} else {
val p = Promise[T]()
using.scheduleOnce(duration) { p completeWith { try value catch { case NonFatal(t) Promise.failed(t).future } } }
def timeoutAfter[T](duration: Duration, using: Scheduler)(timedOutFuture: => Future[T], value: Future[T])
(implicit ec: ExecutionContext): Future[T] = {
Future.firstCompletedOf(Seq(after(duration, using)(timedOutFuture), value))
// Example usage
val processFuture = Future(ProcessedTask(workSender, request, process(workSender, request)))
val timeoutFuture = Promise.successful(TaskTimedOut(workSender, request))
// Send either a TaskTimedOut or a ProcessedTask message to self, whichever completes first
timeoutAfter(Duration(taskTimeoutMs, TimeUnit.MILLISECONDS), context.system.scheduler)(timeoutFuture, processFuture) pipeTo self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.