1
votes

I have following code block which invokes two requests with a slight delay.

    final ActorRef actor1 = getContext().actorOf(
            ActorClass.props(context,
            "actor1");
    futures.add(ask(actor1 , msg1, t));

    final ActorRef actor2 = getContext().actorOf(
            ActorClass.props(context,
            "actor2");
    futures.add(Patterns.after(Duration.create(10000, TimeUnit.MILLISECONDS),
            getContext().system().scheduler() , 
            getContext().dispatcher(), ask(actor2,msg2,t)));

In actor1 and actor2 I am invoking a REST request which returns a cookie along with response message. My intention here is to delay the sending of REST request corresponding to actor2. However what I observed from logs is that the request is sent immediately from both actors and only the response processing (between two futures) is delayed by 10 seconds. Is this intended behavior of scheduler in Akka ? If I want to delay the request initiation between the two actors in above case can I use Thread.sleep ? (I read somewhere that it is not recommended to use Thread.sleep inside an akka actor) . Appreciate inputs.

1

1 Answers

2
votes

The after(..., Future<T>) pattern has different semantics than you assume it to have.

This version of the after pattern will start executing right away, and will delay completing the future yielded from this method. If you however want to delay starting the execution, you'll want to use the after(..., Callable<Future<T>>). In other words, compare these two methods:

// example code in Scala, but uses Java API

// future executes ASAP
print("Hello ")
Patterns.after(1.second, sys.scheduler, sys.dispatcher, Future { println("World!") })

// future executes after 1 second
print("Hello ")
Patterns.after(1.second, sys.scheduler, sys.dispatcher, 
  new Callable[Future[Unit]] {
    override def call() = Future { println("World!") }
  }
)

Happy hakking!