Skip to content

Instantly share code, notes, and snippets.

@alexandru
Last active November 22, 2017 07:07
Show Gist options
  • Save alexandru/87515a72df357aeb9557f74c2ea2c915 to your computer and use it in GitHub Desktop.
Save alexandru/87515a72df357aeb9557f74c2ea2c915 to your computer and use it in GitHub Desktop.
import scala.concurrent.duration._
def scheduleTaskAtFixedRate[A](initialDelay: FiniteDuration, period: FiniteDuration, task: Task[A]): Task[Unit] =
Task.create { (s, callback) =>
def loop(delay: Long): Task[Unit] =
Task.defer {
val startedAt = s.currentTimeMillis()
val t = task.flatMap { _ =>
val duration = s.currentTimeMillis() - startedAt
val nextDelay = {
val v = period.toMillis - duration
if (v < 0) 0 else v
}
loop(nextDelay)
}
if (delay > 0) t.delayExecution(delay.millis) else t
}
loop(initialDelay.toMillis)
.executeWithOptions(_.enableAutoCancelableRunLoops)
.runAsync(callback)(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment