Hyperlinkv0.8.0-beta.28

Cron

Cron.parseconsteffect/Cron.ts:572
(cron: string, tz?: DateTime.TimeZone | string): Result.Result<
  Cron,
  CronParseError
>

Parses a cron expression safely into a Cron instance, returning a Result instead of throwing.

When to use

Use to parse cron expressions from configuration or user input while handling invalid input as a Result.

Details

The expression may contain five fields, where seconds default to 0, or six fields including seconds. Fields support *, comma-separated values, ranges, steps, and month or weekday aliases. Invalid expressions fail with CronParseError.

Example (Parsing cron expressions)

import { Cron, Result } from "effect"
import * as assert from "node:assert"

// At 04:00 on every day-of-month from 8 through 14.
assert.deepStrictEqual(
  Cron.parse("0 0 4 8-14 * *"),
  Result.succeed(Cron.make({
    seconds: [0],
    minutes: [0],
    hours: [4],
    days: [8, 9, 10, 11, 12, 13, 14],
    months: [],
    weekdays: []
  }))
)
constructorsparseUnsafemake
Source effect/Cron.ts:57239 lines
export const parse = (cron: string, tz?: DateTime.TimeZone | string): Result.Result<Cron, CronParseError> => {
  const segments = cron.trim().split(/\s+/).filter(String.isNonEmpty)
  if (segments.length !== 5 && segments.length !== 6) {
    return Result.fail(new CronParseError({ message: `Invalid number of segments in cron expression`, input: cron }))
  }

  if (segments.length === 5) {
    segments.unshift("0")
  }

  const [seconds, minutes, hours, days, months, weekdays] = segments
  const zone = tz === undefined || dateTime.isTimeZone(tz) ?
    Result.succeed(tz) :
    Result.fromOption(
      dateTime.zoneFromString(tz),
      () => new CronParseError({ message: `Invalid time zone in cron expression`, input: tz })
    )

  return Result.all({
    tz: zone,
    seconds: parseSegment(seconds, secondOptions),
    minutes: parseSegment(minutes, minuteOptions),
    hours: parseSegment(hours, hourOptions),
    days: parseSegment(days, dayOptions),
    months: parseSegment(months, monthOptions),
    weekdays: parseSegment(weekdays, weekdayOptions)
  }).pipe(Result.map(({ tz, seconds, minutes, hours, days, months, weekdays }) =>
    make({
      tz,
      seconds: seconds.values,
      minutes: minutes.values,
      hours: hours.values,
      days: days.values,
      months: months.values,
      weekdays: weekdays.values,
      and: (days.wildcard || weekdays.wildcard) && days.values.size !== 0 && weekdays.values.size !== 0
    })
  ))
}
Referenced by 2 symbols