// Cron 表达式解析器 - getgreentool.com // C# WinForms 单文件,零第三方依赖。手写 5 段 cron 解析(分 时 日 月 周)。 // 支持 * , - / 数字、月份/星期英文名、@hourly/@daily/@weekly/@monthly/@yearly/@midnight/@noon/@reboot。 // CLI: --selftest 跑内置断言(兼容末尾多传临时目录参数)。 using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Linq; using System.Text; using System.Windows.Forms; namespace CronApp { // ---------- 纯逻辑层 ---------- public static class CronOps { public static readonly string[] FieldNames = { "分钟", "小时", "日", "月", "星期" }; public static readonly int[] MinVal = { 0, 0, 1, 1, 0 }; public static readonly int[] MaxVal = { 59, 23, 31, 12, 7 }; public static readonly string[] MonthNames = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }; public static readonly string[] WeekNames = { "sun", "mon", "tue", "wed", "thu", "fri", "sat" }; public sealed class CronExpr { public string Original; public HashSet[] Fields; // 0..4 public bool DomRestricted; // 日 是否非 * public bool DowRestricted; // 周 是否非 * } public static string[] Macros = { "@hourly", "0 * * * *", "@daily", "0 0 * * *", "@midnight", "0 0 * * *", "@noon", "0 12 * * *", "@weekly", "0 0 * * 0", "@monthly", "0 0 1 * *", "@yearly", "0 0 1 1 *", "@annually", "0 0 1 1 *", }; // 解析;失败返回 null 并给出中文错误 public static CronExpr Parse(string expr, out string error) { error = null; if (expr == null) { error = "表达式为空"; return null; } string s = expr.Trim().ToLowerInvariant(); if (s.Length == 0) { error = "表达式为空"; return null; } foreach (var m in Macros) { if (m.StartsWith("@") && s == m) { s = Macros[Array.IndexOf(Macros, m) + 1]; break; } } if (s == "@reboot") { error = "@reboot 表示开机时执行一次,没有固定周期,无法计算未来执行时间"; return null; } var parts = s.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 5) { error = "需要 5 段(分 时 日 月 周),现在是 " + parts.Length + " 段"; return null; } var fields = new HashSet[5]; for (int i = 0; i < 5; i++) { fields[i] = ParseField(parts[i], i, out error); if (fields[i] == null) return null; } return new CronExpr { Original = expr.Trim(), Fields = fields, DomRestricted = parts[2] != "*", DowRestricted = parts[4] != "*", }; } private static HashSet ParseField(string part, int idx, out string error) { error = null; var set = new HashSet(); foreach (var seg in part.Split(',')) { string piece = seg; int step = 1; int si = piece.IndexOf('/'); if (si >= 0) { string stepStr = piece.Substring(si + 1); if (!int.TryParse(stepStr, out step) || step < 1) { error = FieldNames[idx] + "段步长无效:" + stepStr; return null; } piece = piece.Substring(0, si); } int lo = MinVal[idx], hi = MaxVal[idx]; if (piece == "*") { if (si < 0) { FillRange(set, lo, hi, idx == 4 ? 7 : hi); continue; } FillRange(set, lo, hi, idx == 4 ? 7 : hi, step); continue; } int dash = piece.IndexOf('-'); if (dash >= 0) { int a = ParseNum(piece.Substring(0, dash), idx, out error); if (error != null) return null; int b = ParseNum(piece.Substring(dash + 1), idx, out error); if (error != null) return null; if (a > b) { error = FieldNames[idx] + "段范围起点 " + a + " 大于终点 " + b; return null; } FillRange(set, a, b, idx == 4 ? 7 : b, si >= 0 ? step : 1); continue; } int v = ParseNum(piece, idx, out error); if (error != null) return null; if (si >= 0) { // "5/10" 表示从 5 开始每 10 FillRange(set, v, MaxVal[idx], idx == 4 ? 7 : MaxVal[idx], step); } else set.Add(v); } return set; } private static void FillRange(HashSet set, int a, int b, int cap, int step = 1) { for (int v = a; v <= b; v += step) set.Add(v); } private static int ParseNum(string t, int idx, out string error) { error = null; t = t.Trim(); if (idx == 3) { int mi = Array.IndexOf(MonthNames, t); if (mi >= 0) return mi + 1; } if (idx == 4) { int wi = Array.IndexOf(WeekNames, t); if (wi >= 0) return wi; } int n; if (!int.TryParse(t, out n)) { error = FieldNames[idx] + "段含无法识别的值:" + t; return 0; } int mx = idx == 4 ? 7 : MaxVal[idx]; if (n < MinVal[idx] || n > mx) { error = FieldNames[idx] + "段取值 " + n + " 超出范围 " + MinVal[idx] + "-" + mx; return 0; } return n; } // 某时刻是否命中 public static bool Matches(CronExpr c, DateTime t) { if (!c.Fields[0].Contains(t.Minute)) return false; if (!c.Fields[1].Contains(t.Hour)) return false; if (!c.Fields[3].Contains(t.Month)) return false; bool domOk = c.Fields[2].Contains(t.Day); int dow = (int)t.DayOfWeek; // 0=周日 bool dowOk = c.Fields[4].Contains(dow) || (dow == 0 && c.Fields[4].Contains(7)); bool domWild = !c.DomRestricted, dowWild = !c.DowRestricted; if (domWild && dowWild) return true; if (domWild) return dowOk; if (dowWild) return domOk; return domOk || dowOk; // 标准 cron:两者都受限时取并集 } // 未来 n 次执行时间 public static List NextRuns(CronExpr c, DateTime from, int n, out string error) { error = null; var list = new List(); DateTime t = new DateTime(from.Year, from.Month, from.Day, from.Hour, from.Minute, 0).AddMinutes(1); // 最多扫 2 年 DateTime limit = from.AddYears(2); while (list.Count < n && t <= limit) { // 月份剪枝 if (!c.Fields[3].Contains(t.Month)) { int y = t.Year, m = t.Month; do { m++; if (m > 12) { m = 1; y++; } } while (y <= limit.Year && !c.Fields[3].Contains(m)); if (y > limit.Year) break; t = new DateTime(y, m, 1, 0, 0, 0); continue; } if (Matches(c, t)) list.Add(t); t = t.AddMinutes(1); } if (list.Count == 0) error = "两年内没有匹配的执行时间(检查「日」与「月」的组合,如 2 月 30 日永远不存在)"; return list; } // 人话描述 public static string Describe(CronExpr c) { var f = c.Fields; string min = DescSimple(f[0], 0, 59, "分"); string hour = DescSimple(f[1], 0, 23, "时"); // 分钟+小时组合 string timeDesc; if (IsFull(f[0], 0, 59) && IsFull(f[1], 0, 23)) timeDesc = "每分钟"; else if (IsFull(f[1], 0, 23)) { int? step = StepOf(f[0], 0, 59); timeDesc = step.HasValue ? "每 " + step.Value + " 分钟" : "每小时第 " + DescSet(f[0]) + " 分"; } else if (f[1].Count == 1) { int h = f[1].First(); timeDesc = IsFull(f[0], 0, 59) ? "每天 " + h + " 点内的每一分钟" : "每天 " + h.ToString("00", CultureInfo.InvariantCulture) + ":" + DescSimple(f[0], 0, 59, "分"); } else timeDesc = "在 " + min + "、" + hour; // 日/周 string domDesc = c.DomRestricted ? "每月 " + DescSet(f[2]) + " 日" : null; string dowDesc = null; if (c.DowRestricted) { dowDesc = "每" + DescWeeks(f[4]); } string monthDesc = IsFull(f[3], 1, 12) ? null : (f[3].Count == 1 ? f[3].First() + " 月" : DescSet(f[3]) + " 月"); var parts = new List(); if (domDesc != null && dowDesc != null) { parts.Add(domDesc + " 或 " + dowDesc); // 并集语义 } else if (domDesc != null) parts.Add(domDesc); else if (dowDesc != null) parts.Add(dowDesc); if (monthDesc != null) parts.Add(monthDesc + "的"); string head = parts.Count > 0 ? string.Join("", parts) + " " : ""; return head + timeDesc; } private static string WeekCn(int w) { string[] cn = { "日", "一", "二", "三", "四", "五", "六" }; return "周" + cn[w == 7 ? 0 : w]; } // 星期集合转「周一至周五」或「周六、周日」式描述 private static string DescWeeks(HashSet s) { var list = s.OrderBy(x => x == 7 ? 0 : x).ToList(); // 周日起排 var parts = new List(); int i = 0; while (i < list.Count) { int j = i; while (j + 1 < list.Count && NextWeek(list[j]) == list[j + 1]) j++; if (j - i >= 2) parts.Add(WeekCn(list[i]) + "至" + WeekCn(list[j])); else for (int k = i; k <= j; k++) parts.Add(WeekCn(list[k])); i = j + 1; } return string.Join("、", parts); } private static int NextWeek(int w) { return (w + 1) % 7; } private static bool IsFull(HashSet s, int lo, int hi) { if (s.Count != hi - lo + 1) return false; for (int v = lo; v <= hi; v++) if (!s.Contains(v)) return false; return true; } // 等差步长探测:0,10,20… 且从下界开始 → 步长 private static int? StepOf(HashSet s, int lo, int hi) { if (s.Count < 2) return null; var list = s.OrderBy(x => x).ToList(); if (list[0] != lo) return null; int d = list[1] - list[0]; if (d <= 1) return null; for (int i = 1; i < list.Count; i++) if (list[i] - list[i - 1] != d) return null; return d; } private static string DescSimple(HashSet s, int lo, int hi, string unit) { if (IsFull(s, lo, hi)) return "每" + unit; // 步长探测 var list = s.OrderBy(x => x).ToList(); if (list.Count > 2 && list[1] - list[0] == list[2] - list[1]) { int d = list[1] - list[0]; bool uniform = true; for (int i = 1; i < list.Count; i++) if (list[i] - list[i - 1] != d) { uniform = false; break; } if (uniform && d > 1 && list[0] == lo) return "每 " + d + " " + unit; } return DescSet(list); } private static string DescSet(HashSet s) { return DescSet(s.OrderBy(x => x).ToList()); } private static string DescSet(List l) { if (l.Count > 8) return l[0] + "-" + l[l.Count - 1] + " 中的 " + l.Count + " 个值"; return string.Join("、", l); } } // ---------- 界面层 ---------- public class MainForm : Form { private TextBox _expr; private Label _desc, _status; private ListBox _next; private Button _btnGo; public MainForm() { Text = "Cron 表达式解析器 - getgreentool.com"; Font = new Font("Microsoft YaHei UI", 9F); ClientSize = new Size(760, 540); StartPosition = FormStartPosition.CenterScreen; var lp = new Label { Text = "Cron 表达式:", AutoSize = true, Location = new Point(10, 14) }; _expr = new TextBox { Font = new Font("Consolas", 11F), Location = new Point(100, 10), Size = new Size(380, 27) }; _btnGo = new Button { Text = "解析", Location = new Point(490, 9), Size = new Size(70, 28) }; var panel = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, WrapContents = true, Location = new Point(10, 44), Size = new Size(740, 40) }; string[][] presets = { new[]{ "每分钟", "* * * * *" }, new[]{ "每小时0分", "0 * * * *" }, new[]{ "每天 08:30", "30 8 * * *" }, new[]{ "工作日 09:00", "0 9 * * 1-5" }, new[]{ "每周一 08:00", "0 8 * * 1" }, new[]{ "每月 1 号 0 点", "0 0 1 * *" }, new[]{ "每 15 分钟", "*/15 * * * *" }, new[]{ "每天 12:00", "0 12 * * *" }, new[]{ "@daily", "@daily" }, new[]{ "@weekly", "@weekly" }, }; foreach (var p in presets) { var b = new Button { Text = p[0], AutoSize = true, Tag = p[1] }; b.Click += (s, e) => { _expr.Text = (string)((Button)s).Tag; DoParse(); }; panel.Controls.Add(b); } var ld = new Label { Text = "含义:", AutoSize = true, Location = new Point(10, 96), ForeColor = Color.DimGray }; _desc = new Label { AutoSize = false, Location = new Point(60, 92), Size = new Size(690, 46), ForeColor = Color.FromArgb(0, 100, 60), Font = new Font("Microsoft YaHei UI", 10.5F, FontStyle.Bold) }; var ln = new Label { Text = "未来 5 次执行时间(从当前时间算起):", AutoSize = true, Location = new Point(10, 146) }; _next = new ListBox { Font = new Font("Consolas", 10.5F), Location = new Point(10, 170), Size = new Size(740, 130), Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right }; var lh = new Label { Text = "字段说明:分(0-59) 时(0-23) 日(1-31) 月(1-12 或 jan-dec) 星期(0-7,0和7都是周日;支持 , - / 和英文名) 宏:@hourly @daily @weekly @monthly @yearly @noon", AutoSize = false, Location = new Point(10, 312), Size = new Size(740, 46), ForeColor = Color.Gray }; _status = new Label { AutoSize = true, Location = new Point(10, 364), ForeColor = Color.Firebrick }; var lg = new Label { Text = "常用参考:", AutoSize = true, Location = new Point(10, 392), ForeColor = Color.DimGray }; var refBox = new TextBox { Multiline = true, ReadOnly = true, BackColor = Color.White, Font = new Font("Consolas", 9.5F), ScrollBars = ScrollBars.Vertical, Location = new Point(10, 414), Size = new Size(740, 110), Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right }; refBox.Text = string.Join("\r\n", new[] { "*/5 * * * * 每 5 分钟 0 9-18 * * * 每天 9 点到 18 点整点", "0 0 * * * 每天零点 0 9 * * 1-5 工作日每天 9 点", "0 0 1 * * 每月 1 号零点 0 0 * * 0 每周日零点", "30 8 1,15 * * 每月 1 号和 15 号 8:30", "注意:日和星期同时指定时,两者是「或」的关系(标准 cron 语义)。", }); Controls.AddRange(new Control[] { lp, _expr, _btnGo, panel, ld, _desc, ln, _next, lh, _status, lg, refBox }); AcceptButton = _btnGo; _btnGo.Click += (s, e) => DoParse(); _expr.Text = "30 8 * * 1-5"; DoParse(); } private void DoParse() { _status.Text = ""; string err; var c = CronOps.Parse(_expr.Text, out err); if (c == null) { _desc.Text = ""; _next.Items.Clear(); _status.Text = "✗ " + err; return; } _desc.Text = "✓ " + CronOps.Describe(c); _next.Items.Clear(); var runs = CronOps.NextRuns(c, DateTime.Now, 5, out err); if (err != null) { _status.Text = "✗ " + err; return; } foreach (var t in runs) _next.Items.Add(t.ToString("yyyy-MM-dd HH:mm (ddd)", CultureInfo.GetCultureInfo("zh-CN"))); } } // ---------- 自测 ---------- public static class SelfTest { private static int _fail; private static void Check(bool ok, string name) { if (!ok) { _fail++; Console.WriteLine("FAIL " + name); } } private static CronOps.CronExpr P(string s) { string e; return CronOps.Parse(s, out e); } public static int RunAll() { _fail = 0; DateTime t0 = new DateTime(2026, 10, 21, 10, 30, 0); // 周三 // 基础解析 Check(P("* * * * *") != null, "全星号合法"); Check(P("0 0 1 1 *") != null, "五段数字合法"); string e1; CronOps.Parse("* * * *", out e1); Check(e1 != null && e1.Contains("5 段"), "四段报错"); string e2; CronOps.Parse("61 * * * *", out e2); Check(e2 != null && e2.Contains("分钟"), "分钟超范围报错"); string e3; CronOps.Parse("* 24 * * *", out e3); Check(e3 != null, "小时超范围报错"); string e4; CronOps.Parse("5-2 * * * *", out e4); Check(e4 != null && e4.Contains("范围起点"), "范围倒置报错"); string e5; CronOps.Parse("abc * * * *", out e5); Check(e5 != null, "字母报错"); Check(P(null) == null, "null报错"); Check(P("") == null, "空串报错"); // 宏 var d = P("@daily"); Check(d != null && d.Fields[0].Contains(0) && d.Fields[1].Contains(0), "@daily=0 0"); Check(P("@weekly").Fields[4].Contains(0), "@weekly周日"); Check(P("@monthly").Fields[2].Contains(1), "@monthly每月1号"); Check(P("@yearly").Fields[3].Contains(1), "@yearly一月"); Check(P("@hourly").Fields[1].Count == 24, "@hourly每小时"); Check(P("@NOON") != null && P("@NOON").Fields[1].Contains(12), "@noon大小写"); string e6; CronOps.Parse("@reboot", out e6); Check(e6 != null && e6.Contains("reboot"), "@reboot专用错误"); // 英文名 Check(P("0 0 * jan *").Fields[3].Contains(1), "jan=1月"); Check(P("0 0 * * mon").Fields[4].Contains(1), "mon=周一"); Check(P("0 0 * * 7").Fields[4].Contains(7) && P("0 0 * * 7").Fields[4].Contains(0) == false, "7=周日"); // 匹配 var c1 = P("*/15 * * * *"); Check(CronOps.Matches(c1, new DateTime(2026, 10, 21, 10, 30, 0)), "*/15命中30分"); Check(!CronOps.Matches(c1, new DateTime(2026, 10, 21, 10, 31, 0)), "*/15不命中31分"); var c2 = P("30 8 * * 1-5"); Check(CronOps.Matches(c2, new DateTime(2026, 10, 21, 8, 30, 0)), "工作日9命中周三"); Check(!CronOps.Matches(c2, new DateTime(2026, 10, 24, 8, 30, 0)), "周六不命中"); var c3 = P("0 0 31 * *"); Check(!CronOps.Matches(c3, new DateTime(2026, 2, 28, 0, 0, 0)), "2月无31日"); // 日+周并集语义 var c4 = P("0 0 1 * 1"); // 1号 或 周一 Check(CronOps.Matches(c4, new DateTime(2026, 11, 2, 0, 0, 0)), "周一命中(并集)"); // 11-2 周一非1号 Check(CronOps.Matches(c4, new DateTime(2026, 12, 1, 0, 0, 0)), "1号命中(并集)"); // 未来执行 string ee; var r1 = CronOps.NextRuns(P("* * * * *"), t0, 3, out ee); Check(r1[0] == new DateTime(2026, 10, 21, 10, 31, 0) && r1[2] == new DateTime(2026, 10, 21, 10, 33, 0), "每分钟未来3次"); var r2 = CronOps.NextRuns(P("0 9 * * *"), t0, 2, out ee); Check(r2[0] == new DateTime(2026, 10, 22, 9, 0, 0), "每天9点下次是明天"); // 今天9点已过 var r3 = CronOps.NextRuns(P("30 8 * * *"), t0, 1, out ee); Check(r3[0] == new DateTime(2026, 10, 22, 8, 30, 0), "8:30明天"); var r4 = CronOps.NextRuns(P("45 10 * * *"), t0, 2, out ee); Check(r4[0] == new DateTime(2026, 10, 21, 10, 45, 0) && r4[1] == new DateTime(2026, 10, 22, 10, 45, 0), "今天稍后+明天"); var r5 = CronOps.NextRuns(P("0 9 * * 1"), t0, 1, out ee); Check(r5[0] == new DateTime(2026, 10, 26, 9, 0, 0), "下次周一9点"); var r6 = CronOps.NextRuns(P("0 0 1 1 *"), t0, 1, out ee); Check(r6[0] == new DateTime(2027, 1, 1, 0, 0, 0), "下次元旦"); var r7 = CronOps.NextRuns(P("*/15 * * * *"), t0, 1, out ee); Check(r7[0] == new DateTime(2026, 10, 21, 10, 45, 0), "*/15下一个整刻"); var r8 = CronOps.NextRuns(P("0 0 * feb *"), t0, 1, out ee); Check(r8[0] == new DateTime(2027, 2, 1, 0, 0, 0), "跨年剪枝到2月"); string e7; CronOps.NextRuns(P("0 0 31 2 *"), t0, 1, out e7); Check(e7 != null && e7.Contains("两年内"), "2月31日永不执行报错"); // 描述 Check(CronOps.Describe(P("30 8 * * *")) == "每天 08:30", "描述每天8:30"); Check(CronOps.Describe(P("* * * * *")) == "每分钟", "描述每分钟"); Check(CronOps.Describe(P("0 * * * *")).Contains("每小时"), "描述每小时"); Check(CronOps.Describe(P("0 9 * * 1-5")).Contains("周一") && CronOps.Describe(P("0 9 * * 1-5")).Contains("周五"), "描述工作日"); Check(CronOps.Describe(P("0 0 1 * *")).Contains("1 日"), "描述每月1号"); Check(CronOps.Describe(P("*/10 * * * *")).Contains("每 10 分"), "描述每10分"); // 边界 Check(P("0 0 30 2 *") != null, "2月30日可解析(执行时提示永不存在)"); Check(P("59 23 31 12 *").Fields[0].Contains(59), "最大值合法"); Check(P("5,15,25 * * * *").Fields[0].Count == 3, "列表3值"); Check(P("1-5/2 * * * *").Fields[0].SetEquals(new HashSet { 1, 3, 5 }), "范围带步长"); Console.WriteLine("SelfTest: " + _fail + " failed"); return _fail == 0 ? 0 : 1; } } public static class CronProgram { [STAThread] public static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(SelfTest.RunAll()); } Application.EnableVisualStyles(); Application.Run(new MainForm()); } } }