Skip to content

Instantly share code, notes, and snippets.

@gekomad
Created January 29, 2025 08:49
Show Gist options
  • Save gekomad/966404b6604308a73630bb7691e192c8 to your computer and use it in GitHub Desktop.
Save gekomad/966404b6604308a73630bb7691e192c8 to your computer and use it in GitHub Desktop.
Crontab in Scala
// libraryDependencies += "com.github.alonsodomin.cron4s" %% "cron4s-core" % "0.8.0"
import java.time.*
import cron4s.*
import cron4s.lib.javatime.*
import scala.concurrent.ExecutionContext.Implicits.global
import scala.annotation.tailrec
import scala.concurrent.Future
final case class Job(name: String) {
println(s"Job($name)")
}
def cron[A](job: => A, cronString: String): Unit = {
val cron = Cron.unsafeParse(cronString)
@tailrec
def go(): Unit = {
val now = ZonedDateTime.now(ZoneId.systemDefault())
cron.next(now) match
case Some(nextTime) =>
val durationUntilNextExecution = Duration.between(now, nextTime)
val s = durationUntilNextExecution.getSeconds() * 1000L
val n = durationUntilNextExecution.getNano() / 1000000L
val mill = s + n
println(s"The next command will be launched in $mill milliseconds")
Thread.sleep(mill)
Future { job }
go()
case _ => ()
}
Future { go() }
}
// run
cron(Job("Tom"), "*/3 * * * * ?")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment