What is the difference between timers.startSingleTimer and scheduler.scheduleOnce in Akka Actor?
Asked Answered
T

1

7

I am designing an actor that should schedule sending a message to itself.

I notice that there are at least two ways to do it.

I would like to understand the difference to choose the right one.

The first is one method of akka.actor.Timers:

def startSingleTimer(key: Any, msg: Any, timeout: FiniteDuration): Unit

The second is the pretty common way with scheduler of actor context system:

final def scheduleOnce(
    delay:    FiniteDuration,
    receiver: ActorRef,
    message:  Any)(implicit executor: ExecutionContext,
                            sender: ActorRef = Actor.noSender): Cancellable

Question:

  • Which is the main difference between them in case of scheduling a message to itself?
  • Is it a good idea to pass actor context to scheduleOnce method?
Tricycle answered 30/1, 2019 at 9:38 Comment(1)
Timers are not thread-safe. It may play difference if you want to use both futures and cancel some timers (because lack of thread-safety means that reference to your timer may be lost).Oubre
C
8

akka.actor.Timers.startSingleTimer

  • Can be used only within an actor
  • Allows only scheduling a message to self, ie not possible to schedule a message to some other actors
  • If actor dies, the active timers are cancelled automatically
  • Keeps track of active timers by user provided key

context.system.scheduler.scheduleOnce

  • Can be used to schedule messages outside and inside actors
  • Requires explicit ActorRef for receiver and optional sender
  • There is no automatic clean-up process. All should be handled explicitly by calling returned akka.actor.Cancellable

So, if you just need to schedule messages to itself, pick akka.actor.Timers

Is it a good idea to pass actor context to scheduleOnce method?

Not sure in what way you want to do it, but in general actor context must be used only within receive method and not passed outside of an actor neither used in callback methods of Futures.

Chesser answered 30/1, 2019 at 9:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.