fthomas / fs2-cron

FS2 streams based on cron expressions

Version Matrix

fs2-cron

GitHub Workflow Status codecov Join the chat at https://gitter.im/fthomas/fs2-cron Scaladex Scaladoc

fs2-cron is a microlibrary that provides FS2 streams based on Cron4s cron expressions.

Examples

import cats.effect.IO
import cats.effect.unsafe.implicits.global
import cron4s.Cron
import eu.timepit.fs2cron.cron4s.Cron4sScheduler
import fs2.Stream
import java.time.LocalTime
val scheduler = Cron4sScheduler.systemDefault[IO]
// scheduler: eu.timepit.fs2cron.Scheduler[IO, cron4s.expr.CronExpr] = eu.timepit.fs2cron.cron4s.Cron4sScheduler$$anon$1@7ba71df2

val evenSeconds = Cron.unsafeParse("*/2 * * ? * *")
// evenSeconds: cron4s.package.CronExpr = CronExpr(
//   seconds = */2,
//   minutes = *,
//   hours = *,
//   daysOfMonth = ?,
//   months = *,
//   daysOfWeek = *
// )

val printTime = Stream.eval(IO(println(LocalTime.now)))
// printTime: Stream[IO, Unit] = Stream(..)

val scheduled = scheduler.awakeEvery(evenSeconds) >> printTime
// scheduled: Stream[IO[x], Unit] = Stream(..)

scheduled.take(3).compile.drain.unsafeRunSync()
// 08:06:40.256
// 08:06:42.003
// 08:06:44.002
val everyFiveSeconds = Cron.unsafeParse("*/5 * * ? * *")
// everyFiveSeconds: cron4s.package.CronExpr = CronExpr(
//   seconds = */5,
//   minutes = *,
//   hours = *,
//   daysOfMonth = ?,
//   months = *,
//   daysOfWeek = *
// )

val scheduledTasks = scheduler.schedule(List(
  evenSeconds      -> Stream.eval(IO(println(LocalTime.now.toString + " task 1"))),
  everyFiveSeconds -> Stream.eval(IO(println(LocalTime.now.toString + " task 2")))
))
// scheduledTasks: Stream[IO, Unit] = Stream(..)

scheduledTasks.take(9).compile.drain.unsafeRunSync()
// 08:06:45.002 task 2
// 08:06:46.002 task 1
// 08:06:48.002 task 1
// 08:06:50.003 task 2
// 08:06:50.003 task 1
// 08:06:52.002 task 1
// 08:06:54.002 task 1
// 08:06:55.002 task 2
// 08:06:56.002 task 1

Using fs2-cron

The latest version of the library is available for Scala 2.12 and 2.13.

If you're using sbt, add the following to your build:

libraryDependencies ++= Seq(
  "eu.timepit" %% "fs2-cron-cron4s" % "0.7.0"
)

License

fs2-cron is licensed under the Apache License, Version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 and also in the LICENSE file.