How can I send a message to an actor with a delay?

How can I send a message to an actor with a delay?

In Akka, you can send a message to an actor with a delay using the scheduler. Here’s how you can do it in both Scala and Java:
Scala:

import system.dispatcher

// Schedules to send the "foo"-message to the testActor after 50ms
system.scheduler.scheduleOnce(50 milliseconds, testActor, "foo")

Java:

system
    .scheduler()
    .scheduleOnce(
        Duration.ofMillis(50), testActor, "foo", system.dispatcher(), ActorRef.noSender());

In the above examples, a message “foo” is scheduled to be sent to the testActor after a delay of 50 milliseconds. The scheduleOnce method is used to schedule the message.

You can also schedule a function to be executed after a delay. Here’s how you can do it:
Scala:

// Schedules a function to be executed (send a message to the testActor) after 50ms
system.scheduler.scheduleOnce(50 milliseconds) {
  testActor ! System.currentTimeMillis
}

Java:

system
    .scheduler()
    .scheduleOnce(
        Duration.ofMillis(50),
        new Runnable() {
          @Override
          public void run() {
            testActor.tell(System.currentTimeMillis(), ActorRef.noSender());
          }
        },
        system.dispatcher());

In these examples, a function that sends the current time to the testActor is scheduled to be executed after a delay of 50 milliseconds.
For more details, you can refer to the Akka Scheduler Documentation.

1 Like

I would also like to add that if you are using the typed API you can use the scheduleOnce in the ActorContext to send a delayed message to another actor.

When scheduling messages to itself the actor can use the TimerScheduler, retrieved from Behaviors.withTimers.