Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a time based watcher to a Scala Future?

I want to add an after(d: FiniteDuration)(callback: => Unit) util to Scala Futures that would enable me to do this:

val f = Future(someTask)

f.after(30.seconds) {
  println("f has not completed in 30 seconds!")
}

f.after(60.seconds) {
  println("f has not completed in 60 seconds!")
}

How can I do this?

like image 459
pathikrit Avatar asked Nov 08 '22 13:11

pathikrit


1 Answers

Usually I use a thread pool executor and promises:

import scala.concurrent.duration._
import java.util.concurrent.{Executors, ScheduledThreadPoolExecutor}
import scala.concurrent.{Future, Promise}

val f: Future[Int] = ???

val executor = new ScheduledThreadPoolExecutor(2, Executors.defaultThreadFactory(), AbortPolicy)

def withDelay[T](operation: ⇒ T)(by: FiniteDuration): Future[T] = {
  val promise = Promise[T]()
  executor.schedule(new Runnable {
    override def run() = {
      promise.complete(Try(operation))
    }
  }, by.length, by.unit)
  promise.future
}

Future.firstCompletedOf(Seq(f, withDelay(println("still going"))(30 seconds)))
Future.firstCompletedOf(Seq(f, withDelay(println("still still going"))(60 seconds)))
like image 122
Ende Neu Avatar answered Nov 14 '22 23:11

Ende Neu