在演员中调用akka scheduler.scheduleOnce不起作用

时间:2016-09-20 05:18:35

标签: akka

我想使用akka系统的调度程序做一些事情间隔

system.scheduler.scheduleOnce(interval.milliseconds, dayActor, DaySwitch)

我工作正常,dayActor将收到DaySwitch消息。

在dayActor中

def receive = {
  case DaySwitch =>
    log.info("begin day switch")
    context.system.scheduler.scheduleOnce(1.day, self, DaySwitch)

一天之后,dayActor没有收到DaySwitch消息。

如何修复它。谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您在启动调度程序时遇到了麻烦,或者在与receive事件进行交互时遇到了麻烦(请提供整个代码)。

case object PullCounter
case class PullResult(counter: Int)
case object PullFailed

class PullActor extends Actor {
  val period = 2.seconds
  var timerCancellable: Option[Cancellable] = None

  def scheduleTimer() = {
    timerCancellable = Some(
      context.system.scheduler.scheduleOnce(
        period, context.self, PullCounter
      )
    )
  }

  override def preStart() = scheduleTimer()

  // so we don't call preStart and schedule a new message
  // see http://doc.akka.io/docs/akka/2.2.4/scala/howto.html
  override def postRestart(reason: Throwable) = {}

  def receive = LoggingReceive {
    case PullCounter =>
      val fReq = Database.fakeRequest()
      fReq.map(counter => PullResult(counter)) pipeTo self
      fReq.onFailure{ case _ => self ! PullFailed }

    case PullFailed =>
      scheduleTimer()

    case r: PullResult =>
      if(r.counter >= 5) {
        context.system.shutdown()
      } else {
        scheduleTimer()
      }
  }
}

我想,像上面这样的例子可以帮助你(至少,它帮助了我类似的情况)。我是从this

取的