Last active
November 22, 2017 07:07
-
-
Save alexandru/87515a72df357aeb9557f74c2ea2c915 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 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