10

I have an akka actor that send messages to itself:

  def receive = {
    while (...) {
       self ! "some message"
    }
  }

I want to use a Throttler to control the flow of messages that this actor sends to itself.

  val throttler = system.actorOf(Props(new TimerBasedThrottler(15 msgsPer (1.minute))))
  throttler ! SetTarget(Some(self))

and then change the while loop to send messages to throttler:

    while (...) {
       throttler ! "some message"
    }

The problem is that I don't know how to access the "system" from inside the actor, to create the throttler. How to do this? Is there any better approach?

Daniel Cukier
  • 11,502
  • 15
  • 68
  • 123

4 Answers4

13

Inside actor, use context.system to access ActorSystem.

Charlie S.
  • 131
  • 1
  • 2
8

Why don't you create the throttler as a child actor?:

def receive = {
    val throttler = context.actorOf(Props(new TimerBasedThrottler(15 msgsPer (1.minute))))
    throttler ! SetTarget(Some(self))
    while (...) {
       throttler ! "some message"
    }
}

Since it makes no sense to let the Throttler alive if the computing actor is dead.

Daniel Cukier
  • 11,502
  • 15
  • 68
  • 123
Mik378
  • 21,881
  • 15
  • 82
  • 180
4

You can use context:

val throttler = context.actorOf(Props(new TimerBasedThrottler(15 msgsPer (1.minute))))
Ende Neu
  • 15,581
  • 5
  • 57
  • 68
4

In Akka you can create an Actor with an Actor System or with an Actor Context, like in:

class FirstActor extends Actor {
  val child = context.actorOf(Props[MyActor], name = "myChild")
  // plus some behavior ...
}

context is a variable available to every Actor.

In case you create the actor with an actor Context it becomes a supervised child of the creating actor, please refer to Akka Docs about supervision and Actor Creation for further information.

Vincenzo Maggio
  • 3,787
  • 26
  • 42