How to get the actor system reference from inside the actor
Asked Answered
D

4

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?

Diplostemonous answered 10/8, 2014 at 21:23 Comment(0)
L
13

Inside actor, use context.system to access ActorSystem.

Longwise answered 31/1, 2017 at 20:5 Comment(0)
C
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.

Contrapuntal answered 10/8, 2014 at 21:28 Comment(0)
S
5

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.

Soane answered 10/8, 2014 at 21:34 Comment(0)
B
4

You can use context:

val throttler = context.actorOf(Props(new TimerBasedThrottler(15 msgsPer (1.minute))))
Buxom answered 10/8, 2014 at 21:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.