21
votes

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())
2
Why 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")S.Karthik

2 Answers

22
votes

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

6
votes

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").