0
class A extends Actor{
def act = {
//do something
}
}
val a = new A
a.join // How Can I implement it
我已閱讀How can I join started Actor? 但是我仍然不知道如何編寫代碼。如何等待演員在斯卡拉停下來
class A extends Actor{
def act = {
//do something
}
}
val a = new A
a.join // How Can I implement it
我已閱讀How can I join started Actor? 但是我仍然不知道如何編寫代碼。如何等待演員在斯卡拉停下來
標準的方式來實現,這將是使用Ask Pattern
它是這樣的:
class MyActor extends Actor {
def receive = {
case "Ping" => sender ! "Pong"
}
}
val future = actor ? "Ping"
val result = Await.result(future, 10 seconds) //blocks until the response has been received, or the timeout reached
這是假設你想從演員的消息封鎖。如果你想知道什麼時候一個演員已經死了,你需要使用臨終看護是這樣的:
case object TellMeWhenActorDies
case object ActorDied
class Watcher extends Actor {
val child = context.actorOf(Props[Watched], "watched")
context.watch(child)
override def receive: Receive = {
case TellMeWhenActorDies => context.become(waitingForDeath(sender))
}
def waitingForDeath(client: ActorRef): Receive = {
case Terminated(name) => client ! ActorDied
}
}
class Watched extends Actor {
override def receive: Receive = {
case _ => //do nothing
}
}
val finishedFuture = supervisor ? TellMeWhenActorDies
system.actorSelection("/user/$a/watched").tell(PoisonPill, supervisor)
Await.result(finishedFuture, 10 seconds)
只需使用gracefulStop模式。這個例子直接來自Akka文檔:
try {
val stopped: Future[Boolean] = gracefulStop(actorRef, 5 seconds, Manager.Shutdown)
Await.result(stopped, 6 seconds)
// the actor has been stopped
} catch {
// the actor wasn't stopped within 5 seconds
case e: akka.pattern.AskTimeoutException =>
}