25
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ScalaのAkka Actorで定期実行する

Last updated at Posted at 2014-03-25

Actorを自分自身で定期的に実行します。

アクター

import akka.actor.Actor

object ScheduledActorProtocol {
  case class Update(target: String)
  case class Schedule(interval: Int)
}

class ScheduledActor extends Actor {
  import SchduledActorProtocol._
  import scala.concurrent.duration._

  val system = context.system
  implicit val executionContext = system.dispatcher

  def receive = {
    case Update(target) =>
      println("update " + target)

    case Schedule(interval) =>
      system.scheduler.schedule(5 seconds, interval seconds, self, "update"))
  }
}

クライアントコード

import akka.actor.{ Props, ActorSystem }
import SchduledActorProtocol._

val scheduledActor = ActorSystem("schedule").actorOf(Props[ScheduledActor])
  dispatchActor ! Schedule(1)

system.scheduler.schedule(5 seconds, interval seconds, self, Update("foo"))

これは、5秒に、interval間隔で、自分のActorRef(self)に、Update("foo")メッセージを送るという意味です。

selfの部分を他のアクターにすれば、そのアクターにメッセージが送信されます。

25
21
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
25
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?