Skip to content

Instantly share code, notes, and snippets.

@gvolpe
Created August 31, 2018 13:10
Show Gist options
  • Select an option

  • Save gvolpe/07db40088b6567167a9eec2bb2cdfdb5 to your computer and use it in GitHub Desktop.

Select an option

Save gvolpe/07db40088b6567167a9eec2bb2cdfdb5 to your computer and use it in GitHub Desktop.
import cats.effect.{ExitCode, IO, IOApp, Timer}
import cats.syntax.apply._
import cats.syntax.functor._
import scala.concurrent.duration._
object scheduler extends IOApp {
def repeatAtFixedRate(period: FiniteDuration, task: IO[Unit])
(implicit timer: Timer[IO]): IO[Unit] =
timer.clock.realTime(MILLISECONDS).flatMap { start =>
task *> timer.clock.realTime(MILLISECONDS).flatMap { finish =>
val nextDelay = period.toMillis - (finish - start)
timer.sleep(nextDelay.millis) *> repeatAtFixedRate(period, task)
}
}
val ioa = IO(println("Hello World!"))
override def run(args: List[String]): IO[ExitCode] =
repeatAtFixedRate(1.second, ioa).as(ExitCode.Success)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment