Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the actor system reference from inside the actor

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?

like image 277
Daniel Cukier Avatar asked Aug 10 '14 21:08

Daniel Cukier


4 Answers

Inside actor, use context.system to access ActorSystem.

like image 168
Charlie S. Avatar answered Nov 05 '22 19:11

Charlie S.


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.

like image 34
Mik378 Avatar answered Nov 05 '22 19:11

Mik378


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.

like image 26
Vincenzo Maggio Avatar answered Nov 05 '22 18:11

Vincenzo Maggio


You can use context:

val throttler = context.actorOf(Props(new TimerBasedThrottler(15 msgsPer (1.minute))))
like image 35
Ende Neu Avatar answered Nov 05 '22 19:11

Ende Neu