From 7babd7290839625216dd33908e6ae16e2b4cef24 Mon Sep 17 00:00:00 2001 From: Elivo Date: Tue, 15 Jul 2025 22:45:13 +0800 Subject: [PATCH] =?UTF-8?q?Cron=20=E5=A2=9E=E5=8A=A0=E5=BC=BA=E5=88=B6?= =?UTF-8?q?=E6=89=93=E6=96=AD=E5=91=BD=E4=BB=A4=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Apewer/CronAttribute.cs | 46 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/Apewer/CronAttribute.cs b/Apewer/CronAttribute.cs index 4835fa4..d005106 100644 --- a/Apewer/CronAttribute.cs +++ b/Apewer/CronAttribute.cs @@ -194,6 +194,7 @@ namespace Apewer static CronAttribute[] _crons = null; static bool _break = false; static DateTime _now; + static int _crons_alive = 0; static CronAttribute[] Init(IEnumerable assemblies, Logger logger, bool logEvent) { @@ -250,6 +251,7 @@ namespace Apewer } // 启动线程。 + _crons_alive = _crons.Length; Console.CancelKeyPress += (s, e) => { _break = true; @@ -261,22 +263,64 @@ namespace Apewer // 监视退出状态。 while (true) { - Thread.Sleep(300); + Thread.Sleep(100); _now = DateTime.Now; var alive = 0; for (var i = 0; i < _crons.Length; i++) if (_crons[i]._alive) alive += 1; if (alive < 1) break; + _crons_alive = alive; } logger.Text(nameof(CronAttribute), "所有 Cron 已结束。"); } } + /// 打断正在执行的 Cron。 + public static void Abort() + { + var crons = _crons; + if (crons != null) + { + foreach (var cron in crons) + { + if (cron == null) continue; + try { cron._thread.Abort(); } catch { } + } + } + } + /// 打断 Cron 循环,不打断正在执行的 Cron。 public static void Break() { _break = true; } + /// 打断 Cron 循环并等待 Cron 执行结束。等待指定的时间后打断正在执行的 Cron。 + /// 强制打断前的等待毫秒数,指定为负数时将无限等待。 + public static void Break(int timeout = 20000) + { + _break = true; + + const int interval = 100; + if (timeout < 0) + { + while (_crons_alive > 0) Thread.Sleep(interval); + return; + } + else + { + if (timeout > 0) + { + var remains = timeout; + while (remains > 0 && _crons_alive > 0) + { + Thread.Sleep(interval); + remains -= interval; + } + } + Abort(); + } + } + /// 获取状态,指示打断 Cron 循环。 public static bool Breaking { get => _break; }