Jet
Jet

Reputation: 3288

How to achieve an akka scheduler inside a loop for the timely ouput

I got a functionality to do something over a timer inside a loop. So I thought of using akka scheduler to achieve it. Here is my sample code (written inside an akka actor) :

class TestActor extends Actor {

  override def receive: Receive = {
    case num: Int => println(num)
    case Tick => loopAndPrint
  }

  def loopAndPrint = {
    val list = List(1, 100, 5, 23)
    list.map { l =>
      context.system.scheduler.scheduleOnce(Duration.create(30, TimeUnit.SECONDS), self, l)
    }
  }

}

I was expecting that the println will be called every 30 seconds until the end of the list. But it started after 30 seconds and ended up printing all the list items at a time.

How can I achieve this to print the list items every 30 seconds after the start ?

Thanks in advance.

Upvotes: 1

Views: 509

Answers (1)

Carlos Galo Campos
Carlos Galo Campos

Reputation: 648

It seems that you loop all the Integer value and schedule a print of each after 30 seconds at once. Try to increment the duration to 30 for each loop.

class TestActor extends Actor {

  override def receive: Receive = {
    case num: Int => println(num)
    case Tick => loopAndPrint
  }

  def loopAndPrint = {
    val list = List(1, 100, 5, 23)
    list.foldLeft(30)((t, l )=> {
      context.system.scheduler.scheduleOnce(Duration.create(t, TimeUnit.SECONDS), self, l)
      t + 30
    })
  }

}

Upvotes: 5

Related Questions