Skip to content

Instantly share code, notes, and snippets.

@henrikengstrom
Created February 16, 2012 08:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henrikengstrom/1843428 to your computer and use it in GitHub Desktop.
Save henrikengstrom/1843428 to your computer and use it in GitHub Desktop.
Akka2.0-RC1 example of using futures to re-start long running task
import akka.actor.{ Props, ActorSystem, Actor }
import akka.pattern.ask
import akka.util.Timeout
import akka.util.duration._
import akka.dispatch.Await
import util.Random
object DangerousOpTest extends App {
println("starting system")
val system = ActorSystem("daOp")
system.actorOf(Props[ActorA]) ! "start"
def done = {
println("shutting system down")
system.shutdown()
}
}
class ActorA extends Actor {
implicit val timeout = Timeout(5000 milliseconds)
def receive = {
case "start" ⇒
println("calling A")
val future = context.actorOf(Props[ActorB]) ? "execute"
future onComplete {
case Right(result) ⇒
println("got result: " + result)
DangerousOpTest.done
case Left(failure) ⇒
println("Got failure: re-running self...")
self ! "start"
}
}
}
class ActorB extends Actor {
lazy val dangerousThingy = new DangerousThingy
def receive = {
case "execute" ⇒
println("executing da op")
sender ! dangerousThingy.doIt
}
}
class DangerousThingy {
def doIt: Int = {
val executionTimeInMillis = new Random().nextInt(20000)
println("sleeping for : " + executionTimeInMillis)
Thread.sleep(executionTimeInMillis)
println("done sleeping for : " + executionTimeInMillis)
executionTimeInMillis
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment