Search code examples
scalaplayframeworkakkaakka-cluster

Akka cluster singleton as scheduler


I am running Play with an Akka cluster. I need an "Singleton Scheduler" to execute some tasks every hour.

What I found out so far is, that I should use ClusterSinglegonManager. But I am not sure how my Actor must look like. In my opinion, I wouldn't need a "receive" Method.

That is, how I instatiate my Singleton:

system.actorOf(
  ClusterSingletonManager.props(
    singletonProps = MySingletonActor.props(configuration),
    terminationMessage = PoisonPill,
    settings = ClusterSingletonManagerSettings(system)),
  name = "mysingletonactor")

That would fit:

object MySingletonActor {
  def props(configuration: Configuration): Props = Props(new MySingletonActor(configuration))
}

class MySingletonActor(configuration: Configuration) extends Actor with ActorLogging {
  context.system.scheduler.schedule(2 seconds, 2 seconds)(println("Hallo Welt"))
  def receive = ???
}

But of course it raises exceptions, because of the missing implementation of the receive method. But it works.

What is the best way to go here? It feels awkward to just schedule a "Tick" and handle the Tick in the receive Method...

class MySingletonActor(configuration: Configuration) extends Actor with ActorLogging {
  case object Tick
  context.system.scheduler.schedule(2 seconds, 2 seconds, self, Tick)
  def receive = { case Tick => println("Hallo Welt") }
}

Is there any kind of a Singleton Scheduler in Akka?


Solution

  • Instead of writing ??? as receive method, you can use Actor.emptyBehavior to not raise an Exception. This is a Receive-expression that matches no messages at all, ever.