LoginSignup
5
5

More than 5 years have passed since last update.

Akka: 5秒おきに処理を行いたい

Posted at

AkkaのActorで数秒おきなど一定間隔で処理を行うには、Schedulerを使うことでできる。

import akka.actor.{ ActorLogging, Actor, ActorSystem, Props }

object Boot extends App {
  val system = ActorSystem("my-actor-system")
  val heartBeat = system.actorOf(Props[HeartBeatActor])
}

import concurrent.duration._
import concurrent.ExecutionContext.Implicits.global

class HeartBeatActor extends Actor with ActorLogging {

  // 5秒おきに "I'm alive" とログに出す
  context.system.scheduler.schedule(0.seconds, 5.seconds)(log.info(s"I'm alive."))

  override def receive: Receive = {
    case _ =>
  }
}

自分自身にメッセージを来る方法もある。何かActor内の状態を変更する場合は、こちらのほうがメッセージがメールボックスにキューイングされるので、スレッドセーフになると思う。

// ...

case object HeartBeat

class HeartBeatActor extends Actor with ActorLogging {
  context.system.scheduler.schedule(0.seconds, 5.seconds, self, HeartBeat)

  override def receive: Receive = {
    case HeartBeat => log.info("I'm alive")
    case _         =>
  }
}
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5