Created
December 22, 2024 09:01
-
-
Save Bunyod/0cd03598e6f33ccc9eb87869987ad741 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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