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?
Inside actor, use context.system to access ActorSystem.
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.
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.
You can use context
:
val throttler = context.actorOf(Props(new TimerBasedThrottler(15 msgsPer (1.minute))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With