/// <summary> /// Create a CronExpression object from a Cron string. /// Cron strings are in the format of "MINUTE HOUR DAY MONTH". /// Each segment of the Cron string can be either an asterisk (*), a number (ex. "30") or multiple numbers (ex. "0,30") /// Example: The Cron string "0,30 * * *" will execute, when the minute mark hits either 0 or 30. The rest of the segments are redundant. /// <param name="cronString">The input Cron string.</param> /// </summary> public CronExpression(string cronString) { if (!CronUtilities.IsExpressionStringValid(cronString)) { throw new System.Exception("Cron expression string is invalid."); } string[] expressionSegments = cronString.Split(' '); this.minute = expressionSegments[0]; this.hour = expressionSegments[1]; this.day = expressionSegments[2]; this.month = expressionSegments[3]; }
/// <summary> /// Returns a DateTime object, with the next time the Cron is expected to execute. /// </summary> public DateTime GetNextRunTime() { string expressionString = GetCronExpressionString(); DateTime now = DateTime.Now; if (!CronUtilities.IsExpressionStringValid(expressionString)) { throw new System.Exception("Cron expression string is invalid."); } // Set the Seconds-value to 0, so the Cron will execute when the minute mark gets reached. now = now.AddSeconds(-now.Second); // If the Cron expression is set to run every minute, // return the current time, plus a minute. if (expressionString == "* * * *") { return(now.AddMinutes(1)); } if (minute != "*") { while (now.Minute != Convert.ToInt32(minute)) { now = now.AddMinutes(1); } } if (hour != "*") { while (now.Hour != Convert.ToInt32(hour)) { now = now.AddHours(1); } } if (day != "*") { while (now.Day != Convert.ToInt32(day)) { now = now.AddDays(1); } } if (month != "*") { while (now.Month != Convert.ToInt32(month)) { now = now.AddMonths(1); } } return(now); }