Getting started
editInstall the package
Add the Meziantou.Framework.Scheduling package to your project:
dotnet package add Meziantou.Framework.SchedulingThe examples of this documentation omit the using directives: they need using Meziantou.Framework.Scheduling;.
The occurrences of a recurrence rule
Parse a rule, then enumerate its occurrences from the start of the series:
var rrule = "FREQ=WEEKLY;BYDAY=MO,WE;COUNT=10";
if (RecurrenceRule.TryParse(rrule, out var rule, out var error))
{
var dtStart = new DateTime(2024, 01, 01, 09, 00, 00); // The DTSTART of the event
var occurrences = rule.GetNextOccurrences(dtStart).ToArray();
Assert.HasCount(10, occurrences);
Assert.Equal(new DateTime(2024, 01, 01, 09, 00, 00), occurrences[0]); // Monday
Assert.Equal(new DateTime(2024, 01, 03, 09, 00, 00), occurrences[1]); // Wednesday
Assert.Equal(new DateTime(2024, 01, 31, 09, 00, 00), occurrences[9]);
}
else
{
Assert.Fail(error);
}- TryParse returns
falseand the reason inerrorwhen the rule is not valid. Parse throws aFormatExceptioninstead. - The date you pass to GetNextOccurrences is the start of the series, the
DTSTARTof an iCalendar event: the first occurrences are computed from it, and the time of the occurrences comes from it. It is not "now": see The start of the series. COUNT=10ends the series after 10 occurrences. A rule withoutCOUNTorUNTILnever ends: take the occurrences you need withTakeorTakeWhile.
The next run of a cron expression
Parse an expression, then get the occurrences from now:
var cron = CronExpression.Parse("0 */15 * * * *");
var startDate = new DateTime(2024, 01, 01, 10, 05, 00); // DateTime.Now
var occurrences = cron.GetNextOccurrences(startDate).Take(10).ToArray();
Assert.HasCount(10, occurrences);
Assert.Equal(new DateTime(2024, 01, 01, 10, 15, 00), occurrences[0]);
Assert.Equal(new DateTime(2024, 01, 01, 10, 30, 00), occurrences[1]);0 */15 * * * * has six fields, the first one being the seconds: second 0 of every 15th minute. The occurrences are on or after the date you pass; replace the fixed date with DateTime.Now in your application.
Next steps
- Recurrence rules: the rule parts and the common schedules.
- Cron expressions: the syntax and the next occurrence.
- Time zones: occurrences that follow daylight saving time.