Skip to content

Instantly share code, notes, and snippets.

@booleguo
Created September 5, 2016 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save booleguo/41f176418002e2e4b9da0eca55ef871e to your computer and use it in GitHub Desktop.
Save booleguo/41f176418002e2e4b9da0eca55ef871e to your computer and use it in GitHub Desktop.
import java.util.Timer
import java.util.TimerTask
import scala.concurrent._
/** Create Future[T] instances which will be completed after a delay.
*/
object TimedEvent {
val timer = new Timer
/** Return a Future which completes successfully with the supplied value after secs seconds. */
def delayedSuccess[T](secs: Int, value: T): Future[T] = {
val result = Promise[T]
timer.schedule(new TimerTask() {
def run() = {
result.success(value)
}
}, secs * 1000)
result.future
}
/** Return a Future which completes failing with an IllegalArgumentException after secs
* seconds. */
def delayedFailure(secs: Int, msg: String): Future[Int] = {
val result = Promise[Int]
timer.schedule(new TimerTask() {
def run() = {
result.failure(new IllegalArgumentException(msg))
}
}, secs * 1000)
result.future
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment