How to get Akka actor by name as an ActorRef?
Solution 1
You can use the method resolveOne
on an ActorSelection to get an ActorRef asynchronously.
implicit val timeout = Timeout(FiniteDuration(1, TimeUnit.SECONDS))
Akka.system.actorSelection("user/" + "somename").resolveOne().onComplete {
case Success(actorRef) => // logic with the actorRef
case Failure(ex) => Logger.warn("user/" + "somename" + " does not exist")
}
ref : http://doc.akka.io/api/akka/2.3.6/index.html#akka.actor.ActorSelection
Solution 2
Looking up Actors by Concrete Path:
To acquire an
ActorRef
that is bound to the life-cycle of a specific actor you need to send a message, such as the built-inIdentify
message, to the actor and use thesender()
reference of a reply from the actor.
But for the case you're describing, it might be more appropriate to use the scheduler to send a message to an ActorRef
you already have (like self
or a new temporary actor), and react to that message by sending a MessageCaseClass
to actorSelection("user/somename")
.
Related videos on Youtube
Comments
-
Kristen almost 4 years
In Akka I can create an actor as follows.
Akka.system(app).actorOf(Props(classOf[UnzipActor]), name="somename")
Then I am in a different class, how can I get this actor?
I can get an
ActorSelection
lazy val unzip: ActorSelection = Akka.system.actorSelection("user/" + "somename")
However, a
ActorSelection
is not what I want; I want anActorRef
. How can I get aActorRef
?I want to have an
ActorRef
since I wish to schedule a call to anActorRef
using the scheduler.Akka.system(app).scheduler.schedule( 5 seconds, 60 seconds, mustBeActorRef, MessageCaseClass())
-
S.Karthik almost 10 yearsWhy you need actor ref, you can send message to actorseletion. However if, you are looking for a child actor within the parent context, you can use getContext().child("somename")
-
-
jsirocchi almost 10 yearssee also here letitcrash.com/post/55504766698/…