davidrpugh
davidrpugh

Reputation: 4563

Schedule repeating event Akka

In an Akka application one can schedule an Actor to do something repeated in the future using context.system.scheduler.schedule and then passing an initialDelay and then an interval. I would like the interval to be random (i.e., draw from say an exponential distribution in the event I wished to model a poisson process).

How can I schedule an event to occur at random points in the future using the Akka Scheduler?

Upvotes: 1

Views: 844

Answers (2)

This could be accomplished with a recursive function:

def doSomething : Unit = ???

def randomIntervalGenerator : FiniteDuration = ???

@scala.annotation.tailrec
def randomSchedule(count : Int) : Unit = 
  if(count > 0) {
    Thread sleep randomIntervalGenerator.toMillis
    doSomething
    randomSchedule(count -1)
  }

Upvotes: 1

Ende Neu
Ende Neu

Reputation: 15773

If I understand your question correctly you want to be able to adjust the interval in the scheduler, that's not possible because of course that is immutable, but you can schedule the same job multiple times using scheduleOnce and adjusting the delay as you go:

case object DoSomething

class MyActor() extends Actor {
  var delay = 10

  context.system.scheduler.scheduleOnce(delay seconds, self, DoSomething)

  def receive: Receive = {
    case DoSomething =>
      doSomething()
  }

  def doSomething(): Unit = {
    /** do something */
    delay = delay * 2
    context.system.scheduler.scheduleOnce(delay seconds, self, DoSomething)
    ()
  }
}

You can schedule once the process and it will trigger the doSomething() method which will queue another scheduled job with a different delay.

Upvotes: 1

Related Questions