Search code examples
c#algorithmcron

Calculate Cron Next Run Time in C#


I have crontab-like scheduler. Time definition "MM HH WD MD M":

MM- minutes
HH- hours
WD- days of week
MD - days of month
M - months

WD, MD and M allow multiple entries and each of params can be null, for example:

^ ^  0, 1  ^ ^      means exucution every minute, every hour, at sunday and mondey, every day<br>

35 15 ^ ^ ^    execution every day at 15.35<br>

The problem is how to calculate next run time, if you know last execution date. I know how to do this using loop (just add 1 minute until it fits the condition), but there must be better way.


Solution

  • I've successfully used NCrontab for exactly this purpose.

    using something like

    var schedule = CrontabSchedule.Parse("15 35 * * *");
    return schedule.GetNextOccurrence(DateTime.Now);