Created
February 3, 2021 00:42
-
-
Save arturopala/5ab72e5144c968d3d32f74640af38563 to your computer and use it in GitHub Desktop.
This file contains 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
import java.util.{Timer, TimerTask} | |
import java.util.Date | |
import scala.concurrent._ | |
import scala.concurrent.duration.FiniteDuration | |
import scala.util.Try | |
import scala.util.Success | |
import scala.util.Failure | |
object Schedule { | |
def apply[T](delay: Long)(body: => Future[T])(implicit ctx: ExecutionContext): Future[T] = | |
makeTask(body)(timer.schedule(_, delay)) | |
def apply[T](date: Date)(body: => Future[T])(implicit ctx: ExecutionContext): Future[T] = | |
makeTask(body)(timer.schedule(_, date)) | |
def apply[T]( | |
delay: FiniteDuration | |
)(body: => Future[T])(implicit ctx: ExecutionContext): Future[T] = | |
makeTask(body)(timer.schedule(_, delay.toMillis)) | |
private val timer = new Timer(true) | |
private def makeTask[T]( | |
body: => Future[T] | |
)(schedule: TimerTask => Unit)(implicit ctx: ExecutionContext): Future[T] = { | |
val prom = Promise[T]() | |
schedule( | |
new TimerTask { | |
def run() { | |
// 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). | |
body.transform( | |
{ result: T => | |
prom.complete(Success(result)) | |
result | |
}, | |
{ error: Throwable => | |
prom.complete(Failure(error)) | |
error | |
} | |
) | |
} | |
} | |
) | |
prom.future | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment