vicaba
vicaba

Reputation: 2876

How to schedule random messages in Akka? (Message reference is always the same)

I'm trying to schedule random messages with Akka scheduler.schedule, something like:

  system.scheduler.schedule(1 second, 5 seconds, actorRef,
    scala.util.Random.nextInt(50))

The problem is that the "Int" reference gets caught and the message the scheduler sends is always the same number. In other words, the random number is only generated once.

I can't come up with a workaround for that. Any help?

Upvotes: 0

Views: 349

Answers (2)

Jatin
Jatin

Reputation: 31724

Is your question to schedule sending of a message at random duration? if so, you could:

import system.dispatcher
def body: () => Unit = () => {
  logServiceRef ! MyMessage("some message")
  system.scheduler.scheduleOnce(FiniteDuration.apply(Random.nextInt(5),TimeUnit.SECONDS)) (body)
}
system.scheduler.scheduleOnce(0 second) (body)

Upvotes: 2

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Use the overloaded schedule method which takes a function to execute periodically. In the function body send the message (random number).

context.system.scheduler.schedule(1 second, 5 second) { actorRef ! Random.nextInt(10) }

This way nextInt will be called every time message is sent to the actor.So new random number will be generated.

Upvotes: 2

Related Questions