Matching Date & Time
To be able to show examples of how to use cron4s, we are going to base them in the brand new Java Time API added to Java 8 as is one of the bests (if not the best) date & time libraries available. To use the built-in support for it we will need the following imports:
import java.time._
import cron4s._
import cron4s.lib.javatime._
Now let’s parse a new expression:
val cron = Cron.unsafeParse("10-35 2,4,6 * * * ?")
// cron: CronExpr = CronExpr(10-35, 2,4,6, *, *, *, ?)
Now we can perform 2 types of matches against any object that extends java.time.Temporal
:
val now = LocalDateTime.of(2016, 12, 1, 0, 4, 9)
// now: LocalDateTime = 2016-12-01T00:04:09
cron.allOf(now)
// res0: Boolean = false
cron.anyOf(now)
// res1: Boolean = true
As said before, these two operations are also available at the sub-expression level:
cron.datePart.allOf(now)
// res2: Boolean = true
cron.datePart.anyOf(now)
// res3: Boolean = true
cron.timePart.allOf(now)
// res4: Boolean = false
cron.timePart.anyOf(now)
// res5: Boolean = true
allOf
will evaluate all the fields of the Cron expression against all the fields
of the DateTime object and it will return false
if there is any one that does
not match the sub-expression corresponding to that field. In the other hand, anyOf
will return true
if there is at least one field in the Cron expression that matches
it corresponding field.
Individual Fields
We can also test if the fields that compound the expression match separately instead of using the whole expression:
cron.seconds.matchesIn(now)
// res6: Boolean = false
cron.minutes.matchesIn(now)
// res7: Boolean = true