I'm trying to find a way how to get a specific value from a CRON expression.
Eg I have this CRON expression "*/5 * * * *"
and I need to get minutes. The result must be 5. All I found it's example of usage NCrontab library. It shows how to get schedule:
var schedule = CrontabSchedule.Parse("*/5 * * * *");
Is there any way to solve this problem?
If you simply need the minutes, you shouldn't need the NCrontab library. You can parse this simple enough yourself.
var expression = "*/5 * * * *";
var split = expression.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (split.Length < 5)
throw new Exception("Invalid CRON expression");
var onlyDigits = "0123456789";
// strip non numeric chars
var minutes = new string(split[0].Where(c => onlyDigits.Contains(c)).ToArray());
I use regular expressions. Try this:
internal static Match GetExpressionRegex(string expression)
=> Regex.Match(
expression,
"(?<Minutes>[0-9*,/-]+) (?<Hours>[0-9*,/-]+) (?<Days>[0-9*,/-]+) (?<Month>[0-9*,/\\-a-z]+) (?<DayOfWeek>[0-9*,/\\-a-z]+)",
RegexOptions.Singleline,
TimeSpan.FromSeconds(0.2)
);
Code Reference: https://github.com/rashadrivera/CronExpression/blob/master/CronExpression/Internals/CronExpressionHelper.cs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.