Skip to content

Instantly share code, notes, and snippets.

@danielhopkins
Created March 17, 2013 20:58
Show Gist options
  • Save danielhopkins/5183625 to your computer and use it in GitHub Desktop.
Save danielhopkins/5183625 to your computer and use it in GitHub Desktop.
Timeouts for actors
/*
The general idea is to handle timeouts as a message instead of using callbacks or worse yet, blocking
the actor (as I do below)
*/
val system = ActorSystem()
val myactor = system.actorOf(Props[MyActor])
val someotheractor = system.actorOf(Props[SomeotherActor])
class MyActor extends Actor with ActorLogging {
def receive = {
case d: DoSomething =>
(someotheractor ! DoSomething) orTimeout(duration = 200.millis, timeoutMessage = Timeout)
// vs.
/*
val f = someotheractor ? DoSomething
val value = Await.result(f, 200.millis)
*/
case t: Timeout =>
sender ! Timeout
}
}
class SomeotherActor extends Actor with ActorLogging {
def recieve = {
case d: DoSomething =>
Thread.sleep(2000)
sender ! d
}
}
class DoSomething {}
class Timeout {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment