Hyperlinkv0.8.0-beta.28

Cron

Cron.matchconsteffect/Cron.ts:678
(cron: Cron, date: DateTime.DateTime.Input): boolean

Returns true when a date/time matches a Cron schedule.

When to use

Use to test whether a specific date/time satisfies a cron schedule.

Details

Seconds, minutes, hours, months, and the optional timezone are checked directly. For day constraints, an empty days or weekdays set means that field matches every value; when both sets are non-empty, a date matches if either the day-of-month or weekday matches.

Example (Matching dates against a schedule)

import { Cron, Result } from "effect"

const cron = Result.getOrThrow(Cron.parse("0 0 4 8-14 * *"))

// Check if specific dates match
const matches1 = Cron.match(cron, new Date("2021-01-08T04:00:00Z"))
console.log(matches1) // true - 4 AM on the 8th

const matches2 = Cron.match(cron, new Date("2021-01-08T05:00:00Z"))
console.log(matches2) // false - wrong hour

const matches3 = Cron.match(cron, new Date("2021-01-07T04:00:00Z"))
console.log(matches3) // false - wrong day
predicatesnextprev
Source effect/Cron.ts:67840 lines
export const match = (cron: Cron, date: DateTime.DateTime.Input): boolean => {
  const parts = dateTime.makeZonedUnsafe(date, {
    timeZone: Option.getOrUndefined(cron.tz)
  }).pipe(dateTime.toParts)

  if (cron.seconds.size !== 0 && !cron.seconds.has(parts.second)) {
    return false
  }

  if (cron.minutes.size !== 0 && !cron.minutes.has(parts.minute)) {
    return false
  }

  if (cron.hours.size !== 0 && !cron.hours.has(parts.hour)) {
    return false
  }

  if (cron.months.size !== 0 && !cron.months.has(parts.month)) {
    return false
  }

  if (cron.days.size === 0 && cron.weekdays.size === 0) {
    return true
  }

  if (cron.and) {
    return (cron.days.size === 0 || cron.days.has(parts.day)) &&
      (cron.weekdays.size === 0 || cron.weekdays.has(parts.weekDay))
  }

  if (cron.weekdays.size === 0) {
    return cron.days.has(parts.day)
  }

  if (cron.days.size === 0) {
    return cron.weekdays.has(parts.weekDay)
  }

  return cron.days.has(parts.day) || cron.weekdays.has(parts.weekDay)
}