Skip to content

Instantly share code, notes, and snippets.

@izmailoff
Created December 21, 2016 08:33
Show Gist options
  • Save izmailoff/bbb52ffab11faafae1a9dab85e9830cd to your computer and use it in GitHub Desktop.
Save izmailoff/bbb52ffab11faafae1a9dab85e9830cd to your computer and use it in GitHub Desktop.
Schedules a task to be run continuously without using Akka system or other schedulers
import scala.concurrent._
import ExecutionContext.Implicits.global
object Main extends App {
def repeatEvery[T](timeoutMillis: Int)(f: => T): Future[T] = {
val p = Promise[T]()
val never = p.future
f
def timeout = Future {
Thread.sleep(timeoutMillis)
throw new TimeoutException
}
val failure = Future.firstCompletedOf(List(never, timeout))
failure.recoverWith { case _ => repeatEvery(timeoutMillis)(f) }
}
repeatEvery(1000) {
println("scheduled job called")
}
println("main started doing its work")
Thread.sleep(10000)
println("main finished")
}
@izmailoff
Copy link
Author

Prints:

scheduled job called
main started doing its work
scheduled job called
scheduled job called
scheduled job called
scheduled job called
scheduled job called
scheduled job called
scheduled job called
scheduled job called
scheduled job called
main finished

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment