Skip to content
Advertisement

Timed behaviors in Akka classic?

I am working with Akka classic, and have to setup timed behaviors – in Akka typed, I could do this using Behaviors.withTimers how do I accomplish this in Akka classic? It seems like we can create an actor in Akka using

public static Props props() {
    return Props.create(actor.class, () -> new actor());
}

How do I use timers in this kind of initialization?

Advertisement

Answer

See the docs on Timers: https://doc.akka.io/docs/akka/current/actors.html#timers-scheduled-messages

In short, mixin the Timers trait. Then you can use timers to access the API. You’ll receive messages in response to the timers firing.

class MyActor extends Actor with Timers {
  import MyActor._
  timers.startSingleTimer(TickKey, FirstTick, 500.millis)

  def receive = {
    case FirstTick =>
      // do something useful here
      timers.startTimerWithFixedDelay(TickKey, Tick, 1.second)
    case Tick =>
    // do something useful here
  }
}
Advertisement