Skip to content

Instantly share code, notes, and snippets.

@fomkin
Created September 28, 2017 20:23
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 fomkin/a6bc62d63e86f4b15f4c8c7593396780 to your computer and use it in GitHub Desktop.
Save fomkin/a6bc62d63e86f4b15f4c8c7593396780 to your computer and use it in GitHub Desktop.
final class JavaTimerScheduler {
private val timer = new Timer()
def scheduleOnce[T](delay: FiniteDuration)(job: => T)(implicit ec: ExecutionContext): JobHandler[T] = {
val promise = Promise[T]
val task = new TimerTask {
def run(): Unit = {
Future {
val result = job // Execute a job
promise.complete(Success(result))
}
}
}
timer.schedule(task, delay.toMillis)
JobHandler(
cancel = () => { task.cancel(); () },
result = promise.future
)
}
def schedule[U](interval: FiniteDuration)(job: => U)(implicit ec: ExecutionContext): Cancel = {
val task = new TimerTask {
def run(): Unit = Future { job }
}
val millis = interval.toMillis
timer.schedule(task, millis, millis)
() => { task.cancel(); () }
}
}
type Cancel = () => Unit
case class JobHandler[+T](
cancel: Cancel,
result: Future[T]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment