Phil
Phil

Reputation: 50346

How to get Akka actor by name as an ActorRef?

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 an ActorRef. How can I get a ActorRef?

I want to have an ActorRef since I wish to schedule a call to an ActorRef using the scheduler.

Akka.system(app).scheduler.schedule(
  5 seconds, 60 seconds, mustBeActorRef, MessageCaseClass())

Upvotes: 23

Views: 26347

Answers (2)

Arnaud Gourlay
Arnaud Gourlay

Reputation: 4666

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

Upvotes: 26

Chris Martin
Chris Martin

Reputation: 30736

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-in Identify message, to the actor and use the sender() 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").

Upvotes: 7

Related Questions