0

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?

vicaba
  • 2,836
  • 1
  • 27
  • 45

2 Answers2

2

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.

Nagarjuna Pamu
  • 14,737
  • 3
  • 22
  • 40
2

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)
Jatin
  • 31,116
  • 15
  • 98
  • 163