如何在Play Framework关闭期间等待演员停止?

时间:2013-10-16 20:10:36

标签: scala playframework-2.2

以下代码在关闭播放服务器时抛出 java.lang.IllegalMonitorStateException 异常;它是由 onStop 方法中的 a.wait(1000)调用引起的。谁能告诉我为什么会这样,以及如何优雅地等待演员在Play框架关闭中完成?

import play.api.GlobalSettings
import play.api.libs.concurrent.Akka
import akka.actor.{ Actor, Props }
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.Play.current
import models.{ TestActor, StartMessage, StopMessage }

object Global extends GlobalSettings {

    override def onStart(application : play.api.Application) {
        val a = Akka.system.actorOf(Props[TestActor], name = "test-actor")
        a ! StartMessage("Start instruction")

    }

    override def onStop(application : play.api.Application) {
        val a = Akka.system.actorSelection("akka://application/user/test-actor")
        a ! StopMessage("Stop instruction")
        a.wait(1000)
        Akka.system.shutdown()
    }
}

更新

以下是完整的解决方案,并采用以下答案:

import play.api.GlobalSettings
import play.api.libs.concurrent.Akka
import akka.actor.{ Actor, Props }
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.Play.current
import models.{ TestActor, StartMessage, StopMessage }
import akka.pattern.gracefulStop
import scala.concurrent.Future
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.Await
import com.typesafe.config.impl.ResolveContext
import com.typesafe.config.impl.ResolveContext
import akka.actor.ActorIdentity

object Global extends GlobalSettings {

    override def onStart(application : play.api.Application) {
        val a = Akka.system.actorOf(Props[TestActor], name = "test-actor")
        a ! StartMessage("Start Instruction")
    }

    override def onStop(application : play.api.Application) {
        val a = Akka.system.actorFor("akka://application/user/test-actor")
        a ! StopMessage("Stop Instruction")

        try {
            val stopped : Future[Boolean] = gracefulStop(a, scala.concurrent.duration.Duration(5, "seconds"))
            Await.result(stopped, scala.concurrent.duration.Duration(6, "seconds"))
            // the actor has been stopped
        }
        catch {
            case e : akka.pattern.AskTimeoutException => // the actor wasn't stopped within 5 seconds
        }

        Akka.system.shutdown()
        Akka.system.awaitTermination()
    }
}

1 个答案:

答案 0 :(得分:7)

“优雅的停止 如果您需要等待终止或组合多个actor的有序终止,gracefulStop非常有用:

import akka.pattern.gracefulStop
import akka.dispatch.Await
import akka.actor.ActorTimeoutException

try {
  val stopped: Future[Boolean] = gracefulStop(actorRef, 5 seconds)(system)
  Await.result(stopped, 6 seconds)
  // the actor has been stopped
} catch {
  case e: ActorTimeoutException ⇒ // the actor wasn't stopped within 5 seconds
}

PS。谷歌搜索“优雅的演员akka”给出了答案作为最佳结果。