Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala looping for certain duration

Tags:

loops

scala

akka

I'm looking for a possibility to loop for certain duration. For example, I'd like to println("Hi there!") for 5 minutes.

I'm using Scala and Akka.

I was thinking about using future, which will be finished in 5 minutes, meanwhile I would use while cycle on it with check that it's not completed. Such approach doesn't work for me, as my class isn't an actor, and I cant finish the future from outside the loop.

Any ideas or maybe there are ready solutions for such things?

Current ugly solution:

    def now = Calendar.getInstance.getTime.getTime
    val ms = durationInMins * 60 * 1000
    val finish = now + ms

    while (now <= finish) {
       println("hi")
    }

Thanks in advance!

like image 664
psisoyev Avatar asked Aug 21 '13 13:08

psisoyev


1 Answers

The solution of @Radian is potentially dangerous, as it will eventually block all the threads in the ExecutorService, when your app runs this code several times concurrently. You can better use a Deadline for that:

import scala.concurrent.duration._

val deadline = 5.seconds.fromNow

while(deadline.hasTimeLeft) {
  // ...
}
like image 200
drexin Avatar answered Sep 20 '22 00:09

drexin