Skip to content

Instantly share code, notes, and snippets.

@ericacm
Last active July 11, 2016 22:32
Show Gist options
  • Save ericacm/3804710 to your computer and use it in GitHub Desktop.
Save ericacm/3804710 to your computer and use it in GitHub Desktop.
Future timeout support
import akka.util.{Duration, NonFatal}
import akka.actor.Scheduler
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 } } }
p.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