Skip to content

CronExpression

Namespace AgentPrism · Assembly AgentPrism.Core.dll

A hand-written parser for the standard five-field cron subset (minute hour day-of-month month day-of-week).

public sealed class CronExpression

objectCronExpression

object.GetType(), object.ToString(), object.Equals(object?), object.Equals(object?, object?), object.ReferenceEquals(object?, object?), object.GetHashCode()

No package is taken on: Cronos or NCrontab are small packages, but every new dependency passes through to the consumer. The five-field parser is ~150 lines and easy to test.

Supported syntax: *, a fixed value, an N-M range, a value1,value2,... list, and /step (may be appended to any of the above). Vixie-cron extensions such as a seconds field, L, W, and # are not supported and are rejected during parsing with a FormatException.

If day-of-week and day-of-month are both restricted (neither is *), the standard cron rule applies: a match occurs when either one holds (OR), not both at once.

GetNextOccurrence(DateTimeOffset, TimeZoneInfo)

Section titled “ GetNextOccurrence(DateTimeOffset, TimeZoneInfo)”

Computes the first time after the given instant that matches the expression.

public DateTimeOffset GetNextOccurrence(DateTimeOffset afterUtc, TimeZoneInfo timeZone)

afterUtc DateTimeOffset

The instant the search starts from (UTC, exclusive).

timeZone TimeZoneInfo

The time zone the expression is interpreted in.

DateTimeOffset

The next run time (UTC).

When daylight saving time skips forward, some local minutes never occur; these minutes are silently skipped. When the clock is set back, one minute occurs twice; TimeZoneInfo.ConvertTimeToUtc picks the first (earlier) occurrence by default.

ArgumentNullException

timeZone is null.

InvalidOperationException

No matching time was found within 4 years.

Parses a cron expression.

public static CronExpression Parse(string expression)

expression string

A five-field cron expression.

CronExpression

The parsed expression.

ArgumentException

expression is empty or whitespace only.

FormatException

The expression does not have five fields, or contains unsupported syntax.

Attempts to parse a cron expression.

public static bool TryParse(string expression, out CronExpression? result)

expression string

A five-field cron expression.

result CronExpression?

The parsed expression, if successful.

bool

true if parsing succeeded.