Skip to content

Instantly share code, notes, and snippets.

@Bunyod
Created December 22, 2024 09:01
Show Gist options
  • Save Bunyod/0cd03598e6f33ccc9eb87869987ad741 to your computer and use it in GitHub Desktop.
Save Bunyod/0cd03598e6f33ccc9eb87869987ad741 to your computer and use it in GitHub Desktop.
object DelayedFuture {
import java.util.{Timer, TimerTask}
import java.util.Date
import scala.concurrent._
import scala.concurrent.duration.FiniteDuration
private val timer = new Timer(true)
private def makeTask[T](
body: => Future[T]
)(schedule: TimerTask => Unit)(implicit ctx: ExecutionContext): Future[T] = {
val promise = Promise[T]()
schedule(
new TimerTask {
def run(): Unit = {
// IMPORTANT: The timer task just starts the execution on the passed
// ExecutionContext and is thus almost instantaneous (making it
// practical to use a single Timer - hence a single background thread).
ctx.execute(() => { promise.completeWith(body) }
)
}
}
)
promise.future
}
def apply[T](delay: FiniteDuration)(body: => Future[T])(implicit ctx: ExecutionContext): Future[T] = {
makeTask(body)(timer.schedule(_, delay.toMillis))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment