Class CronExpression
- Namespace
- Quartz
- Assembly
- Quartz.dll
Provides a parser and evaluator for unix-like cron expressions. Cron expressions provide the ability to specify complex time combinations such as "At 8:00am every Monday through Friday" or "At 1:30am every last Friday of the month".
[Serializable]
public sealed class CronExpression : ISerializable, IEquatable<CronExpression>, IParsable<CronExpression>
- Inheritance
-
CronExpression
- Implements
- Inherited Members
Remarks
Cron expressions are comprised of 6 required fields and one optional field separated by white space. The fields respectively are described as follows:
| Field Name | Allowed Values | Allowed Special Characters | ||
|---|---|---|---|---|
| Seconds | 0-59 | , - /// / | ||
| Minutes | 0-59 | , - /// / | ||
| Hours | 0-23 | , - /// / | ||
| Day-of-month | 1-31 | , - /// ? / L W C | ||
| Month | 1-12 or JAN-DEC | , - /// / | ||
| Day-of-Week | 1-7 or SUN-SAT | , - /// ? / L # | ||
| Year (Optional) | empty, 1970-(the current year plus 100) | , - /// / |
The '*' character is used to specify all values. For example, "*" in the minute field means "every minute".
The '?' character is allowed for the day-of-month and day-of-week fields. It is used to specify 'no specific value', and is a synonym for '*' there: both say that the field names no days, so the other field decides. When both day fields name days the expression fires on the union of the two, and when neither does it fires every day.
The '-' character is used to specify ranges. For example "10-12" in the hour field means "the hours 10, 11 and 12".
The ',' character is used to specify additional values. For example "MON,WED,FRI" in the day-of-week field means "the days Monday, Wednesday, and Friday".
The '/' character is used to specify increments. For example "0/15" in the seconds field means "the seconds 0, 15, 30, and 45". And "5/15" in the seconds field means "the seconds 5, 20, 35, and 50". Specifying '*' before the '/' is equivalent to specifying 0 is the value to start with. Essentially, for each field in the expression, there is a set of numbers that can be turned on or off. For seconds and minutes, the numbers range from 0 to 59. For hours 0 to 23, for days of the month 1 to 31, and for months 1 to 12. The "/" character simply helps you turn on every "nth" value in the given set. Thus, "7/6" in the month field only turns on month "7", it does NOT mean every 6th month, please note that subtlety.
The 'L' character is allowed for the day-of-month and day-of-week fields. This character is short-hand for "last", but it has different meaning in each of the two fields. For example, the value "L" in the day-of-month field means "the last day of the month" - day 31 for January, day 28 for February on non-leap years. If used in the day-of-week field by itself, it simply means "7" or "SAT". But if used in the day-of-week field after another value, it means "the last xxx day of the month" - for example "6L" means "the last friday of the month". You can also specify an offset from the last day of the month, such as "L-3" which would mean the third-to-last day of the calendar month. When using the 'L' option, it is important not to specify lists, or ranges of values, as you'll get confusing/unexpected results.
The 'W' character is allowed for the day-of-month field. This character is used to specify the weekday (Monday-Friday) nearest the given day. As an example, if you were to specify "15W" as the value for the day-of-month field, the meaning is: "the nearest weekday to the 15th of the month". So if the 15th is a Saturday, the trigger will fire on Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th. However, if you specify "1W" as the value for day-of-month, and the 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not 'jump' over the boundary of a month's days. The 'W' character can only be specified when the day-of-month is a single day, not a range or list of days.
The 'L' and 'W' characters can also be combined for the day-of-month expression to yield 'LW', which translates to "last weekday of the month".
The '#' character is allowed for the day-of-week field. This character is used to specify "the nth" XXX day of the month. For example, the value of "6#3" in the day-of-week field means the third Friday of the month (day 6 = Friday and "#3" = the 3rd one in the month). Other examples: "2#1" = the first Monday of the month and "4#5" = the fifth Wednesday of the month. Note that if you specify "#5" and there is not 5 of the given day-of-week in the month, then no firing will occur that month. If the '#' character is used, there can only be one expression in the day-of-week field ("3#1,6#3" is not valid, since there are two expressions).
The legal characters and the names of months and days of the week are not case-sensitive.
NOTES:
- Support for specifying both a day-of-week and a day-of-month value is not complete (you'll need to use the '?' character in one of these fields).
- Overflowing ranges are supported - that is, having a larger number on the left-hand side than the right. You might do 22-2 to catch 10 o'clock at night until 2 o'clock in the morning, or you might have NOV-FEB. It is very important to note that overuse of overflowing ranges creates ranges that don't make sense and no effort has been made to determine which interpretation CronExpression chooses. An example would be "0 0 14-6 ? * FRI-MON".
Constructors
CronExpression(string)
Constructs a new CronExpressionString based on the specified parameter.
public CronExpression(string cronExpression)
Parameters
cronExpressionstringString representation of the cron expression the new object should represent
Remarks
An @ macro - @yearly, @annually, @monthly, @weekly,
@daily, @midnight or @hourly - is expanded here, which is what puts it
behind every entry point that reads an expression string. The expansion is what
CronExpressionString then holds, in the same way that it holds
MON-FRI for a caller who wrote mon-fri.
Exceptions
- ArgumentNullException
cronExpressionis null.- FormatException
cronExpressionis not a valid cron expression.
CronExpression(string, TimeZoneInfo?)
Constructs a new CronExpression resolved in the given time zone.
public CronExpression(string cronExpression, TimeZoneInfo? timeZone)
Parameters
cronExpressionstringString representation of the cron expression the new object should represent
timeZoneTimeZoneInfoThe time zone the expression's times are resolved in; null means the system's local time zone.
Properties
CronExpressionString
Gets the cron expression string.
public string CronExpressionString { get; }
Property Value
- string
The cron expression string.
TimeZone
Gets the time zone the expression's times are resolved in. Defaults to the system's local time zone.
public TimeZoneInfo TimeZone { get; }
Property Value
Remarks
A CronExpression is immutable; use WithTimeZone(TimeZoneInfo?) to get a copy resolved in another time zone.
Methods
Equals(CronExpression?)
Determines whether the specified CronExpression is equal to the current CronExpression.
public bool Equals(CronExpression? other)
Parameters
otherCronExpressionThe CronExpression to compare with the current CronExpression.
Returns
- bool
true if the specified CronExpression is equal to the current CronExpression; otherwise, false.
Equals(object?)
public override bool Equals(object? obj)
Parameters
Returns
GetHashCode()
Serves as a hash function for a particular type.
public override int GetHashCode()
Returns
GetNextInvalidTimeAfter(DateTimeOffset)
Returns the next date/time after the given date/time which does not satisfy the expression.
public DateTimeOffset? GetNextInvalidTimeAfter(DateTimeOffset date)
Parameters
dateDateTimeOffsetthe date/time at which to begin the search for the next invalid date/time
Returns
- DateTimeOffset?
The first whole second at or after
datethat this expression does not fire at, or null when it fires at every second through to the give-up year.
Remarks
The expression fires on whole seconds, so the answer is the first whole second at or after
date that it does not fire at. It is read off the expression's own field
sets rather than walked to: the complement of a cron field is as enumerable as the field is,
so a run of firing seconds is stepped over a minute, an hour, a day or a month at a time.
An expression can fire at every second there is — * * * * * ? is the plain one — and
then there is no such time to return. That answers null rather than walking a
century, one second at a time, to the year the scheduler gives up looking for a fire in.
GetNextValidTimeAfter(DateTimeOffset)
Returns the next date/time after the given date/time which satisfies the cron expression.
public DateTimeOffset? GetNextValidTimeAfter(DateTimeOffset date)
Parameters
dateDateTimeOffsetthe date/time at which to begin the search for the next valid date/time
Returns
- DateTimeOffset?
the next valid date/time
GetObjectData(SerializationInfo, StreamingContext)
Writes this expression's fields into a serialization payload.
[SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
Parameters
infoSerializationInfoThe payload being written.
contextStreamingContextThe serialization context.
GetPreviousValidTimeBefore(DateTimeOffset)
Returns the latest time before endTime that this expression fires at,
the mirror of GetNextValidTimeAfter(DateTimeOffset).
public DateTimeOffset? GetPreviousValidTimeBefore(DateTimeOffset endTime)
Parameters
endTimeDateTimeOffsetThe instant to search back from; the result is strictly before it.
Returns
- DateTimeOffset?
The preceding fire time, or null when the expression has none.
IsSatisfiedBy(DateTimeOffset)
Indicates whether the given date satisfies the cron expression.
public bool IsSatisfiedBy(DateTimeOffset dateUtc)
Parameters
dateUtcDateTimeOffsetThe date to evaluate.
Returns
- bool
a boolean indicating whether the given date satisfies the cron expression
Remarks
Note that milliseconds are ignored, so two Dates falling on different milliseconds of the same second will always have the same result here.
Parse(string)
Parses a cron expression string into a CronExpression.
public static CronExpression Parse(string cronExpression)
Parameters
cronExpressionstringString representation of the cron expression.
Returns
- CronExpression
The parsed expression.
Exceptions
- ArgumentNullException
cronExpressionis null.- FormatException
cronExpressionis not a valid cron expression.
Parse(string, CronFormat)
Parses a cron expression string written in the given format into a CronExpression.
public static CronExpression Parse(string cronExpression, CronFormat format)
Parameters
cronExpressionstringString representation of the cron expression.
formatCronFormatThe dialect
cronExpressionis written in.
Returns
- CronExpression
The parsed expression.
Remarks
Unix reads the five-field crontab form, whose day-of-week is numbered
0-7 with both 0 and 7 meaning Sunday. The result is an ordinary CronExpression
holding the canonical Quartz spelling of the same schedule, so "30 4 * * 1" becomes
"0 30 4 ? * MON" and that is what CronExpressionString, the dashboard and
the database show. The format is not recorded anywhere and the original text is not recoverable.
A time zone composes: CronExpression.Parse(s, CronFormat.Unix).WithTimeZone(tz).
Exceptions
- ArgumentNullException
cronExpressionis null.- ArgumentOutOfRangeException
formatis not a cron format.- FormatException
cronExpressionis not a valid cron expression informat.
ParseWithHash(string, CronFormat, int)
Parses a cron expression string written in the given format, whose H (hash) tokens are
resolved against the given integer seed.
public static CronExpression ParseWithHash(string cronExpression, CronFormat format, int hashSeed)
Parameters
cronExpressionstringCron expression that may contain
Htokens.formatCronFormatThe dialect
cronExpressionis written in.hashSeedintAn integer seed the hash values are derived from.
Returns
- CronExpression
The parsed expression, with every
Htoken resolved to a value.
Remarks
The expression is read as the Quartz expression that says the same thing before its H
tokens are resolved, so a token is hashed over the range the field has in Quartz — an H
in a five-field day-of-week is spread over 1-7, not 0-7. What comes back is an ordinary
CronExpression in the canonical Quartz spelling, as
Parse(string, CronFormat) describes.
Exceptions
- ArgumentNullException
cronExpressionis null.- FormatException
cronExpressionis not a valid cron expression informat.
- See Also
ParseWithHash(string, CronFormat, string)
Parses a cron expression string written in the given format, whose H (hash) tokens are
resolved against the given hash key.
public static CronExpression ParseWithHash(string cronExpression, CronFormat format, string hashKey)
Parameters
cronExpressionstringCron expression that may contain
Htokens.formatCronFormatThe dialect
cronExpressionis written in.hashKeystringA stable string key the hash values are derived from (e.g. the trigger name).
Returns
- CronExpression
The parsed expression, with every
Htoken resolved to a value.
Remarks
The expression is read as the Quartz expression that says the same thing before its H
tokens are resolved, so a token is hashed over the range the field has in Quartz — an H
in a five-field day-of-week is spread over 1-7, not 0-7. What comes back is an ordinary
CronExpression in the canonical Quartz spelling, as
Parse(string, CronFormat) describes.
Exceptions
- ArgumentNullException
cronExpressionorhashKeyis null.- FormatException
cronExpressionis not a valid cron expression informat.
- See Also
ParseWithHash(string, int)
Parses a cron expression string whose H (hash) tokens are resolved against the given
integer seed.
public static CronExpression ParseWithHash(string cronExpression, int hashSeed)
Parameters
cronExpressionstringCron expression that may contain
Htokens.hashSeedintAn integer seed the hash values are derived from.
Returns
- CronExpression
The parsed expression, with every
Htoken resolved to a value.
Exceptions
- ArgumentNullException
cronExpressionis null.- FormatException
cronExpressionis not a valid cron expression.
- See Also
ParseWithHash(string, string)
Parses a cron expression string whose H (hash) tokens are resolved against the given
hash key. The key is typically the trigger or job name, so that every trigger written with the
same expression lands on a different minute instead of all firing at once.
public static CronExpression ParseWithHash(string cronExpression, string hashKey)
Parameters
cronExpressionstringCron expression that may contain
Htokens.hashKeystringA stable string key the hash values are derived from (e.g. the trigger name).
Returns
- CronExpression
The parsed expression, with every
Htoken resolved to a value.
Exceptions
- ArgumentNullException
cronExpressionorhashKeyis null.- FormatException
cronExpressionis not a valid cron expression.
- See Also
ResolveHash(string, int)
Resolves H (hash) tokens in a cron expression to deterministic numeric values based on the given integer seed.
public static string ResolveHash(string cronExpression, int hashSeed)
Parameters
cronExpressionstringCron expression that may contain H tokens
hashSeedintAn integer seed used to derive hash values
Returns
- string
A standard cron expression string with all H tokens resolved to numeric values
Remarks
A leading @ macro is expanded first, as the constructor expands it, so a macro means the
same schedule here as everywhere else.
ResolveHash(string, string)
Resolves H (hash) tokens in a cron expression to deterministic numeric values based on the given hash key. The resulting expression is a standard cron expression with no H tokens.
public static string ResolveHash(string cronExpression, string hashKey)
Parameters
cronExpressionstringCron expression that may contain H tokens
hashKeystringA stable string key used to derive hash values (e.g., trigger name)
Returns
- string
A standard cron expression string with all H tokens resolved to numeric values
Remarks
The H symbol can be thought of as a deterministic value over a range, derived from a hash of the key. It produces stable scheduling that spreads load across time.
Supported H token forms:
H— hash value within the full range of the fieldH(min-max)— hash value within the specified rangeH/step— hash-derived offset, then every stepH(min-max)/step— hash-derived offset in range, then every step
A leading @ macro is expanded first, as the constructor expands it, so a macro means the
same schedule here as everywhere else. A macro names a whole schedule and so carries no
H token; it simply passes through with nothing to resolve.
ToString()
Returns the string representation of the CronExpression
public override string ToString()
Returns
- string
The string representation of the CronExpression
TryParse(string?, out CronExpression?)
Attempts to parse a cron expression string into a CronExpression.
public static bool TryParse(string? cronExpression, out CronExpression? result)
Parameters
cronExpressionstringString representation of the cron expression; may be null.
resultCronExpressionThe parsed expression, or null when parsing failed.
Returns
TryParse(string?, CronFormat, out CronExpression?)
Attempts to parse a cron expression string written in the given format into a CronExpression.
public static bool TryParse(string? cronExpression, CronFormat format, out CronExpression? result)
Parameters
cronExpressionstringString representation of the cron expression; may be null.
formatCronFormatThe dialect
cronExpressionis written in.resultCronExpressionThe parsed expression, or null when parsing failed.
Returns
- bool
true when
cronExpressionis a valid cron expression informat. An undefinedformatanswers false as well: aTrythat throws is aTryits caller has to wrap, which is the thing it exists to save them.
- See Also
TryParseWithHash(string?, CronFormat, string, out CronExpression?)
Attempts to parse a cron expression string written in the given format, whose H (hash)
tokens are resolved against the given hash key.
public static bool TryParseWithHash(string? cronExpression, CronFormat format, string hashKey, out CronExpression? result)
Parameters
cronExpressionstringCron expression that may contain
Htokens; may be null.formatCronFormatThe dialect
cronExpressionis written in.hashKeystringA stable string key the hash values are derived from (e.g. the trigger name).
resultCronExpressionThe parsed expression, or null when parsing failed.
Returns
Remarks
The expression is read as the Quartz expression that says the same thing before its H
tokens are resolved, so a token is hashed over the range the field has in Quartz — an H
in a five-field day-of-week is spread over 1-7, not 0-7. What comes back is an ordinary
CronExpression in the canonical Quartz spelling, as
Parse(string, CronFormat) describes.
Exceptions
- ArgumentNullException
hashKeyis null.
- See Also
TryParseWithHash(string?, string, out CronExpression?)
Attempts to parse a cron expression string whose H (hash) tokens are resolved against
the given hash key.
public static bool TryParseWithHash(string? cronExpression, string hashKey, out CronExpression? result)
Parameters
cronExpressionstringCron expression that may contain
Htokens; may be null.hashKeystringA stable string key the hash values are derived from (e.g. the trigger name).
resultCronExpressionThe parsed expression, or null when parsing failed.
Returns
Remarks
An H token can be malformed in its own right — H(0-60) names a minute that does
not exist — so the resolution is inside the attempt rather than ahead of it.
Exceptions
- ArgumentNullException
hashKeyis null.
WithTimeZone(TimeZoneInfo?)
Returns a copy of this expression resolved in the given time zone.
public CronExpression WithTimeZone(TimeZoneInfo? timeZone)
Parameters
timeZoneTimeZoneInfoThe time zone the copy's times are resolved in; null means the system's local time zone.
Returns
- CronExpression
A new CronExpression with the same expression string, or this instance when the time zone would not change.