From 37e3840359f7761db2d411911c8f02caea394f44 Mon Sep 17 00:00:00 2001 From: zhuweiye Date: Sat, 21 Nov 2026 23:05:43 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(core):=20cron=20=E8=A1=A8=E8=BE=BE?= =?UTF-8?q?=E5=BC=8F=E8=A7=A3=E6=9E=90=E4=B8=8E=E8=B0=83=E5=BA=A6=E5=99=A8?= =?UTF-8?q?=EF=BC=88issue=20#72=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 `uvcpp_cron_schedule` + `uvcpp_cron`(`src/uvcpp/uvcpp_cron.*`): - 表达式:5 段(分 时 日 月 周)或 6 段(秒 分 时 日 月 周),支持 `*`、`n`、 `a-b`、`a-b/n`、逗号列表;越界/倒序/步长 0/段数不对一律解析失败并给原因, 不猜 `JAN`/`@daily`/`L/W/#` 这些扩展; - 时间基准 **UTC**(不读本机时区,容器/CI 里可复现); - 日与周同时受限时按 Vixie 语义取"或"(`0 0 13 * 5` = 13 号或周五); - `next_utc()` 严格晚于给定时刻,5 年上限内无解返回 false(`0 0 30 2 *`); - `uvcpp_cron` 绑一条 `uvcpp_loop`,每任务一个 `uvcpp_timer`;错过不补, 回调异常被吞掉并计 `stats().errors`,`start/stop/clear/stats` 齐全; - 解析与求下次时间是纯函数,可脱离循环单独用。 用例 `cron_func`:17 条解析(含 12 条非法)、UTC 匹配(周一/13 号或周五的 "或"语义)、`*/15` 跨刻、跨月、6 段下一秒、2 月 30 号无解,以及真 `uvcpp_loop` 上每秒触发的调度(正常任务 + 抛异常任务并行,errors/runs/jobs 对账)。文档 `doc/lowlevel-guide.md` §11。 本地 build-all 163/163、build-h3/default 编过;文档门禁全绿。 --- doc/lowlevel-guide.md | 26 ++- src/uvcpp/uvcpp_cron.cpp | 335 +++++++++++++++++++++++++++++++++ src/uvcpp/uvcpp_cron.h | 161 ++++++++++++++++ tests/functional/cron_func.cpp | 175 +++++++++++++++++ 4 files changed, 696 insertions(+), 1 deletion(-) create mode 100644 src/uvcpp/uvcpp_cron.cpp create mode 100644 src/uvcpp/uvcpp_cron.h create mode 100644 tests/functional/cron_func.cpp diff --git a/doc/lowlevel-guide.md b/doc/lowlevel-guide.md index c8011ca2..58ebf100 100644 --- a/doc/lowlevel-guide.md +++ b/doc/lowlevel-guide.md @@ -1,4 +1,4 @@ -# 低层指南:循环、句柄与请求 +# 低层指南:循环、句柄与请求 `src/handle/`、`src/req/`、`src/uvcpp/` 是这一层:libuv 的薄封装。**handle** 是长期挂在 循环上的对象(定时器、信号、流、进程),**req** 是一次性的操作(写、连、DNS、文件)。 @@ -26,6 +26,7 @@ 8. [错误与异常](#8-错误与异常) 9. [典型坑](#9-典型坑) 10. [没做的(如实列出)](#10-没做的如实列出) +11. [定时任务(cron)](#11-定时任务cron) --- @@ -375,6 +376,29 @@ int main() { --- +## 11. 定时任务(cron) + +`uvcpp_cron`(`#include `)是核心层的小调度器: + +```cpp +// doc-snippet: fragment — 装配摘录,不是完整翻译单元。 +uvcpp::uvcpp_cron cron(&loop); // 绑一条循环,回调在它的线程上 +cron.add("0 3 * * *", [] { backup(); }); // 每天 03:00(UTC) +cron.add("*/5 * * * * *", [] { heartbeat(); }); // 6 段:每 5 秒 +cron.start(); // 在 loop.run() 之前 +``` + +- **表达式**:5 段(分 时 日 月 周)或 6 段(秒 分 时 日 月 周);`*`、`n`、 + `a-b`、`a-b/n`、逗号列表。不支持 `JAN`/`MON`、`@daily`、`L/W/#`。 +- **时间基准是 UTC**(不读本机时区);要按本地时间跑,在回调里换算或按 UTC 写。 +- **日与周同时受限时按"或"**(Vixie cron 语义):`0 0 13 * 5` = 13 号**或**周五。 +- `uvcpp_cron_schedule::parse()` + `next_utc()` 可单独当纯函数用(不挂循环), + 适合"算下次触发时间"塞进自己的调度器。 +- 每个任务一个 `uvcpp_timer`;**错过不补**,回调抛异常被吞掉并计 `stats().errors`。 +- 用例:`tests/functional/cron_func.cpp`。 + +--- + 相关文档:[net 网络层指南](./net-guide.md)、[TLS 与证书指南](./ssl-guide.md)、 [项目 README](../README.zh.md)。 diff --git a/src/uvcpp/uvcpp_cron.cpp b/src/uvcpp/uvcpp_cron.cpp new file mode 100644 index 00000000..dbd185f7 --- /dev/null +++ b/src/uvcpp/uvcpp_cron.cpp @@ -0,0 +1,335 @@ +/** + * @file src/uvcpp/uvcpp_cron.cpp + * @brief cron 解析与调度器的实现。 + * @author zhuweiye + * @version 1.0.0 + */ + +#include "uvcpp/uvcpp_cron.h" + +#include +#include + +#include +#include +#include +#include + +namespace uvcpp { + +namespace { + +typedef std::vector bitfield; + +bitfield make_bits(int hi) { return bitfield((hi / 64) + 1, 0); } +void set_bit(bitfield& f, int v) { f[v / 64] |= (uint64_t(1) << (v % 64)); } +bool get_bit(const bitfield& f, int v) { + return (f[v / 64] & (uint64_t(1) << (v % 64))) != 0; +} + +bool all_digits(const std::string& s) { + if (s.empty()) return false; + for (size_t i = 0; i < s.size(); ++i) { + if (s[i] < '0' || s[i] > '9') return false; + } + return true; +} + +bool to_int(const std::string& s, int& out) { + if (!all_digits(s)) return false; + out = static_cast(std::strtol(s.c_str(), nullptr, 10)); + return true; +} + +bool parse_field(const std::string& spec, int lo, int hi, bitfield& out, + bool dow_norm, std::string* err) { + out = make_bits(hi); + std::istringstream items(spec); + std::string item; + bool any = false; + while (std::getline(items, item, ',')) { + if (item.empty()) { + if (err) *err = "空的列表项"; + return false; + } + std::string range = item; + int step = 1; + const size_t slash = item.find('/'); + if (slash != std::string::npos) { + range = item.substr(0, slash); + const std::string ss = item.substr(slash + 1); + if (!to_int(ss, step) || step <= 0) { + if (err) *err = "步长不是正整数:'" + ss + "'"; + return false; + } + } + int a = 0, b = 0; + if (range == "*") { + a = lo; + b = hi; + } else { + const size_t dash = range.find('-'); + if (dash == std::string::npos) { + if (!to_int(range, a)) { + if (err) *err = "不是数字:'" + range + "'"; + return false; + } + b = a; + // `a/n` 是常见写法(从 a 起到上界按步长);Vixie 只认 `a-b/n`, + // 这里接受前者,语义按"a..hi"。 + if (slash != std::string::npos) b = hi; + } else { + if (!to_int(range.substr(0, dash), a) || + !to_int(range.substr(dash + 1), b)) { + if (err) *err = "区间两端不是数字:'" + range + "'"; + return false; + } + } + } + if (a < lo || b > hi || a > b) { + if (err) { + *err = "越界或倒序:" + std::string("[") + std::to_string(lo) + "," + + std::to_string(hi) + "] 内的 '" + item + "'"; + } + return false; + } + for (int v = a; v <= b; v += step) { + set_bit(out, dow_norm && v == 7 ? 0 : v); + any = true; + } + } + return any; +} + +std::vector split_ws(const std::string& s) { + std::vector out; + std::istringstream in(s); + std::string w; + while (in >> w) out.push_back(w); + return out; +} + +void gmtime_utc(std::time_t t, struct tm& tmv) { +#ifdef _WIN32 + ::gmtime_s(&tmv, &t); +#else + ::gmtime_r(&t, &tmv); +#endif +} + +} // namespace + +uvcpp_cron_schedule::uvcpp_cron_schedule() { + seconds_ = make_bits(59); + minutes_ = make_bits(59); + hours_ = make_bits(23); + days_ = make_bits(31); + months_ = make_bits(12); + weekdays_ = make_bits(7); +} + +bool uvcpp_cron_schedule::parse(const std::string& expr, + uvcpp_cron_schedule& out, + std::string* err) { + const std::vector f = split_ws(expr); + if (f.size() != 5 && f.size() != 6) { + if (err) *err = "需要 5 段或 6 段,实际 " + std::to_string(f.size()); + return false; + } + + uvcpp_cron_schedule r; + r.expr_ = expr; + size_t i = 0; + if (f.size() == 6) { + r.has_seconds_ = true; + if (!parse_field(f[i++], 0, 59, r.seconds_, false, err)) return false; + } else { + r.seconds_ = make_bits(59); + for (int s = 0; s < 60; ++s) set_bit(r.seconds_, s); + } + if (!parse_field(f[i++], 0, 59, r.minutes_, false, err)) return false; + if (!parse_field(f[i++], 0, 23, r.hours_, false, err)) return false; + if (!parse_field(f[i++], 1, 31, r.days_, false, err)) return false; + if (!parse_field(f[i++], 1, 12, r.months_, false, err)) return false; + if (!parse_field(f[i++], 0, 7, r.weekdays_, true, err)) return false; + // 原始字段串判"是不是 `*`":日/周同时受限时 Vixie 语义才用"或"。 + r.dom_star_ = (f.size() == 6 ? f[3] : f[2]) == "*"; + r.dow_star_ = (f.size() == 6 ? f[5] : f[4]) == "*"; + r.valid_ = true; + out = r; + return true; +} + +bool uvcpp_cron_schedule::bit(const std::vector& f, int v) const { + return get_bit(f, v); +} + +bool uvcpp_cron_schedule::matches_utc(std::time_t t) const { + if (!valid_) return false; + struct tm tmv; + gmtime_utc(t, tmv); + if (!bit(seconds_, tmv.tm_sec)) return false; + if (!bit(minutes_, tmv.tm_min)) return false; + if (!bit(hours_, tmv.tm_hour)) return false; + if (!bit(months_, tmv.tm_mon + 1)) return false; + const bool dom = bit(days_, tmv.tm_mday); + const bool dow = bit(weekdays_, tmv.tm_wday); + if (dom_star_ && dow_star_) return true; + if (dom_star_) return dow; + if (dow_star_) return dom; + return dom || dow; // Vixie:两者都受限时取"或" +} + +bool uvcpp_cron_schedule::next_utc(std::time_t after, + std::time_t& next) const { + if (!valid_) return false; + const long long step = has_seconds_ ? 1 : 60; + // 5 年上限:2 月 29/30 这种"永远不成立"的表达式要能返回 false 而不是死循环。 + const long long cap = step == 1 ? 366LL * 24 * 3600 * 2 : 5LL * 366 * 24 * 60; + long long t = static_cast(after) + step; + for (long long k = 0; k < cap; ++k, t += step) { + if (matches_utc(static_cast(t))) { + next = static_cast(t); + return true; + } + } + return false; +} + +// =========================================================================== +// 调度器 +// =========================================================================== + +struct uvcpp_cron::job { + uvcpp_cron_schedule schedule; + std::function cb; + uvcpp_timer* timer = nullptr; + bool armed = false; +}; + +struct uvcpp_cron::impl { + uvcpp_loop* loop = nullptr; + std::vector jobs; + bool running = false; + uvcpp_cron_stats s; + + void arm(job* j) { + std::time_t next = 0; + if (!j->schedule.next_utc(std::time(nullptr), next)) { + j->armed = false; + return; + } + const std::time_t now = std::time(nullptr); + uint64_t ms = next > now + ? static_cast(next - now) * 1000 + : 1; + j->timer->start( + [this, j](uvcpp_timer*) { fire(j); }, ms, 0); + j->armed = true; + } + + void fire(job* j) { + const std::time_t fired_at = std::time(nullptr); + try { + if (j->cb) j->cb(); + ++s.runs; + } catch (...) { + ++s.errors; + } + // 错过不补:从"现在"重新算;若回调耗时跨过了本应触发的下一拍, + // next_utc 会自然给出更晚的一拍,这里只把 skipped 记下来(可观测性)。 + std::time_t next = 0; + if (!j->schedule.next_utc(fired_at, next)) { + j->armed = false; + return; + } + const std::time_t now = std::time(nullptr); + if (next <= now) { + // 已经错过的触发不补;从 now 再求一次。 + if (!j->schedule.next_utc(now, next)) { + j->armed = false; + return; + } + ++s.skipped; + } + uint64_t ms = next > now ? static_cast(next - now) * 1000 : 1; + j->timer->start([this, j](uvcpp_timer*) { fire(j); }, ms, 0); + j->armed = true; + } +}; + +uvcpp_cron::uvcpp_cron(uvcpp_loop* loop) : impl_(new impl()) { + impl_->loop = loop; + if (loop == nullptr) { + // 无循环 = 只能当解析器用;add() 一律返回 UV_EINVAL。 + return; + } +} + +uvcpp_cron::~uvcpp_cron() { + clear(); + delete impl_; +} + +int uvcpp_cron::add(const std::string& expr, std::function cb, + std::string* err) { + if (impl_->loop == nullptr) { + if (err) *err = "调度器没有循环"; + return UV_EINVAL; + } + uvcpp_cron_schedule schedule; + if (!uvcpp_cron_schedule::parse(expr, schedule, err)) return UV_EINVAL; + if (!cb) { + if (err) *err = "回调为空"; + return UV_EINVAL; + } + job* j = new job(); + j->schedule = schedule; + j->cb = std::move(cb); + j->timer = new uvcpp_timer(impl_->loop); + impl_->jobs.push_back(j); + impl_->s.jobs = impl_->jobs.size(); + if (impl_->running) { + impl_->arm(j); + } + return 0; +} + +void uvcpp_cron::start() { + if (impl_->loop == nullptr || impl_->running) return; + impl_->running = true; + for (size_t i = 0; i < impl_->jobs.size(); ++i) impl_->arm(impl_->jobs[i]); +} + +void uvcpp_cron::stop() { + impl_->running = false; + for (size_t i = 0; i < impl_->jobs.size(); ++i) { + if (impl_->jobs[i]->timer != nullptr) { + impl_->jobs[i]->timer->stop(); + impl_->jobs[i]->armed = false; + } + } +} + +void uvcpp_cron::clear() { + for (size_t i = 0; i < impl_->jobs.size(); ++i) { + job* j = impl_->jobs[i]; + if (j->timer != nullptr) { + j->timer->stop(); + delete j->timer; + } + delete j; + } + impl_->jobs.clear(); + impl_->s.jobs = 0; +} + +size_t uvcpp_cron::size() const { return impl_->jobs.size(); } + +uvcpp_cron_stats uvcpp_cron::stats() const { + uvcpp_cron_stats out = impl_->s; + out.jobs = impl_->jobs.size(); + return out; +} + +} // namespace uvcpp diff --git a/src/uvcpp/uvcpp_cron.h b/src/uvcpp/uvcpp_cron.h new file mode 100644 index 00000000..477c0a73 --- /dev/null +++ b/src/uvcpp/uvcpp_cron.h @@ -0,0 +1,161 @@ +/** + * @file src/uvcpp/uvcpp_cron.h + * @brief 定时任务:cron 表达式解析 + 挂在 `uvcpp_loop` 上的调度器。 + * @author zhuweiye + * @version 1.0.0 + * + * ```cpp + * uvcpp::uvcpp_cron cron(loop); + * cron.add("0 3 * * *", [] { backup(); }); // 每天 03:00(UTC) + * cron.add("* * * * * *", [] { tick(); }); // 6 段:每秒(测试/心跳用) + * cron.start(); + * ``` + * + * ## 时间基准是 **UTC** + * + * 所有匹配与下次触发都按 UTC(`gmtime_r`)。理由:本库跨平台(Windows 没有 + * `tzset` 语义一致的环境变量路径),"本地时区"在容器/CI 里也常常不是部署者 + * 以为的那个;要按本地时间跑,调用方在自己的回调里换算,或表达式按 UTC 写。 + * + * ## 支持哪些表达式 + * + * - **5 段**(标准 Vixie cron):`分 时 日 月 周`; + * - **6 段**(Quartz 风格扩展):`秒 分 时 日 月 周`; + * - 每段支持 `*`、`n`、`a-b`、`a-b/n`、``*`` 配步长(星号斜杠 n)、逗号列表; + * - 周:`0`/`7` 都是周日;月:`1-12`;日:`1-31`; + * - **日与周同时受限时按"或"**(Vixie cron 的语义:`0 0 13 * 5` 是"13 号 + * 或周五",不是"13 号的周五"); + * - 不支持名字(`JAN`/`MON`)、`@daily` 这类宏、秒级之外的 L/W/# 扩展 —— + * 遇到就是解析失败,不猜。 + * + * ## 调度语义 + * + * - **错过不补**:回调执行的耗时超过间隔时,下一次从"现在"重新算,不会把 + * 错过的每一拍都补跑(`stats().skipped` 记这种情况)。 + * - 回调抛异常会被吞掉并计 `errors`,不影响后续触发。 + * - 只在构造时给的循环线程上跑;`add()` / `start()` 请在 `loop.run()` 之前或 + * 用 `loop.post()` 投回来。 + * - 每个任务一个 `uvcpp_timer`;任务多(上千)时请合并成更少的定时器再用 + * 表达式的时间字段自己分派 —— 本类没有做定时器堆。 + */ + +#pragma once +#ifndef SRC_UVCPP_UVCPP_CRON_H +#define SRC_UVCPP_UVCPP_CRON_H + +#include +#include + +#include +#include +#include +#include +#include + +namespace uvcpp { + +class uvcpp_loop; +class uvcpp_timer; + +/** + * @brief 解析好的 cron 表达式。可用作纯函数(`next_utc()`)不接受调度器。 + */ +class UVCPP_API uvcpp_cron_schedule { + public: + uvcpp_cron_schedule(); + + /** + * @brief 解析一个表达式(5 段或 6 段)。 + * + * @param expr 表达式(首尾空白忽略,段间任意空白)。 + * @param out 成功时写入解析结果。 + * @param err 失败时写入人读原因(可为 nullptr)。 + * @return 是否成功。 + */ + static bool parse(const std::string& expr, uvcpp_cron_schedule& out, + std::string* err = nullptr); + + bool valid() const { return valid_; } + /// 是否 6 段(带秒)。 + bool has_seconds() const { return has_seconds_; } + const std::string& expression() const { return expr_; } + + /// `t`(UTC)是否命中。无效表达式恒 false。 + bool matches_utc(std::time_t t) const; + + /** + * @brief 严格晚于 @p after 的下一次触发(UTC)。 + * + * @param next 成功时写入下一次触发时间。 + * @return false = 无效表达式,或搜索上限(5 年)内没有匹配 + * (例如 `0 0 30 2 *` 这种永远不存在的日期)。 + */ + bool next_utc(std::time_t after, std::time_t& next) const; + + private: + friend class uvcpp_cron; + bool bit(const std::vector& f, int v) const; + + std::vector seconds_; ///< 60 位;5 段表达式恒全 1(每秒都可) + std::vector minutes_; ///< 60 位 + std::vector hours_; ///< 24 位 + std::vector days_; ///< 32 位(1..31 用) + std::vector months_; ///< 13 位 + std::vector weekdays_; ///< 8 位(0..7,7 归一成 0) + bool dom_star_ = true; + bool dow_star_ = true; + bool has_seconds_ = false; + bool valid_ = false; + std::string expr_; +}; + +struct UVCPP_API uvcpp_cron_stats { + uint64_t runs = 0; ///< 成功执行的回调次数 + uint64_t errors = 0; ///< 回调抛异常的次数 + uint64_t skipped = 0; ///< 因回调耗时超过间隔而跳过的触发次数 + size_t jobs = 0; ///< 当前任务数 +}; + +/** + * @brief 挂在一条 `uvcpp_loop` 上的 cron 调度器。见文件头。 + */ +class UVCPP_API uvcpp_cron { + public: + explicit uvcpp_cron(uvcpp_loop* loop); + ~uvcpp_cron(); + + uvcpp_cron(const uvcpp_cron&) = delete; + uvcpp_cron& operator=(const uvcpp_cron&) = delete; + + /** + * @brief 加一个任务。解析失败返回 `UV_EINVAL` 并写 @p err。 + * + * 调度器已经 `start()` 时,新任务当场排上;没 `start()` 时等 `start()`。 + */ + int add(const std::string& expr, std::function cb, + std::string* err = nullptr); + + /// 开始触发(幂等)。 + void start(); + + /// 暂停全部触发(幂等);任务保留,`start()` 可再开。 + void stop(); + + /// 摘掉全部任务(停掉它们的定时器)。 + void clear(); + + size_t size() const; + + uvcpp_cron_stats stats() const; + + private: + struct job; + struct impl; + // impl 用裸指针:`uvcpp_timer` 的句柄必须在循环线程上析构,而析构顺序由 + // 用户在 `loop.run()` 之后控制;这里只按任务生命周期管理。 + impl* impl_; +}; + +} // namespace uvcpp + +#endif // SRC_UVCPP_UVCPP_CRON_H diff --git a/tests/functional/cron_func.cpp b/tests/functional/cron_func.cpp new file mode 100644 index 00000000..9d9fc074 --- /dev/null +++ b/tests/functional/cron_func.cpp @@ -0,0 +1,175 @@ +/** + * @file tests/functional/cron_func.cpp + * @brief cron 表达式解析、UTC 匹配、下次触发时间,以及真循环上的调度。 + * + * 三层判据: + * + * 1. **解析**:合法/非法表达式(越界、倒序、步长 0、段数不对); + * 2. **纯函数**:`matches_utc()` 与 `next_utc()` —— 用固定 UTC 时间点比对, + * 不依赖本机时区;日与周同时受限时按 Vixie 的"或"语义; + * 3. **调度**:一条真 `uvcpp_loop` 上跑 6 段表达式(每秒),确认回调真的被 + * 触发、抛异常的任务被计数且不影响别的任务。 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace uvcpp; + +namespace { + +int g_fail = 0; + +void check(bool ok, const std::string& what) { + if (ok) { + std::cout << " [ ok ] " << what << std::endl; + } else { + ++g_fail; + std::cerr << " [FAIL] " << what << std::endl; + } +} + +/// 构造一个 UTC 的 `time_t`(`timegm` 在 Windows 上叫 `_mkgmtime`)。 +std::time_t utc(int y, int mon, int d, int h, int mi, int s) { + struct tm tmv; + std::memset(&tmv, 0, sizeof(tmv)); + tmv.tm_year = y - 1900; + tmv.tm_mon = mon - 1; + tmv.tm_mday = d; + tmv.tm_hour = h; + tmv.tm_min = mi; + tmv.tm_sec = s; +#ifdef _WIN32 + return ::_mkgmtime(&tmv); +#else + return ::timegm(&tmv); +#endif +} + +void test_parse() { + std::cout << "-- 解析 --" << std::endl; + uvcpp_cron_schedule sc; + std::string err; + check(uvcpp_cron_schedule::parse("* * * * *", sc, &err), "5 段 * 合法"); + check(!sc.has_seconds(), "5 段没有秒字段"); + check(uvcpp_cron_schedule::parse("*/15 0-6 * * 1-5", sc, &err), + "带步长与区间的 5 段合法"); + check(uvcpp_cron_schedule::parse("* * * * * *", sc, &err), "6 段合法"); + check(sc.has_seconds(), "6 段有秒字段"); + + const char* bad[] = {"", "* * * *", "* * * * * * *", "60 * * * *", + "0 24 * * *", "0 0 0 * *", "0 0 * 13 *", + "0 0 * * 8", "5-1 * * * *", "*/0 * * * *", + "a * * * *", "1,,2 * * * *"}; + for (size_t i = 0; i < sizeof(bad) / sizeof(bad[0]); ++i) { + std::string e; + check(!uvcpp_cron_schedule::parse(bad[i], sc, &e), + std::string("拒绝非法表达式 '") + bad[i] + "'(" + e + ")"); + } +} + +void test_match_and_next() { + std::cout << "-- 匹配 / 下次触发(UTC)--" << std::endl; + uvcpp_cron_schedule sc; + + // 2026-01-05 是周一(周四 1 号 → 5 号周一)。 + const std::time_t mon1030 = utc(2026, 1, 5, 10, 30, 0); + uvcpp_cron_schedule::parse("30 10 * * 1", sc); + check(sc.matches_utc(mon1030), "周一 10:30 命中 '30 10 * * 1'"); + check(!sc.matches_utc(mon1030 + 60), "下一分钟不命中"); + + // 日/周同时受限:13 号 *或* 周五。 + uvcpp_cron_schedule::parse("0 0 13 * 5", sc); + const std::time_t tue13 = utc(2026, 1, 13, 0, 0, 0); // 周二,13 号 + const std::time_t fri16 = utc(2026, 1, 16, 0, 0, 0); // 周五,16 号 + const std::time_t wed14 = utc(2026, 1, 14, 0, 0, 0); + check(sc.matches_utc(tue13), "13 号(周二)命中(日的分支)"); + check(sc.matches_utc(fri16), "周五(16 号)命中(周的分支)"); + check(!sc.matches_utc(wed14), "周三 14 号不命中(不是'13 号的周五')"); + + // next_utc:从 10:07 起,*/15 的下一拍是 10:15。 + uvcpp_cron_schedule::parse("*/15 * * * *", sc); + std::time_t next = 0; + check(sc.next_utc(utc(2026, 1, 5, 10, 7, 0), next) && + next == utc(2026, 1, 5, 10, 15, 0), + "*/15:10:07 → 10:15"); + + // 跨月:每月 1 号 0 点。 + uvcpp_cron_schedule::parse("0 0 1 * *", sc); + check(sc.next_utc(utc(2026, 1, 5, 10, 7, 0), next) && + next == utc(2026, 2, 1, 0, 0, 0), + "每月 1 号 0 点:1/5 → 2/1"); + + // 6 段:严格晚一秒。 + uvcpp_cron_schedule::parse("* * * * * *", sc); + const std::time_t t = utc(2026, 1, 5, 10, 7, 30); + check(sc.next_utc(t, next) && next == t + 1, "6 段:下一秒"); + + // 永远不存在的日期:搜索上限内返回 false(2 月 30 号)。 + uvcpp_cron_schedule::parse("0 0 30 2 *", sc); + check(!sc.next_utc(utc(2026, 1, 1, 0, 0, 0), next), + "2 月 30 号:上限内无解 → false"); +} + +void test_scheduler() { + std::cout << "-- 调度(真循环)--" << std::endl; + uvcpp_loop loop; + uvcpp_timer stopper(&loop); + // 3 秒后停循环(在循环线程上拨 stop,避免跨线程调 uv_stop)。 + stopper.start([&loop](uvcpp_timer*) { loop.stop(); }, 3000, 0); + + uvcpp_cron cron(&loop); + std::atomic ticks(0); + std::atomic throws(0); + std::string err; + check(cron.add("* * * * * *", [&ticks] { ++ticks; }, &err) == 0, + "加任务成功(" + err + ")"); + check(cron.add("* * * * * *", + [&throws] { + ++throws; + throw std::runtime_error("boom"); + }, + &err) == 0, + "加抛异常的任务成功"); + check(cron.size() == 2, "任务数 = 2"); + cron.start(); + + std::thread th([&loop] { loop.run(); }); + th.join(); + cron.stop(); + + const uvcpp_cron_stats s = cron.stats(); + check(ticks.load() >= 1, "正常任务至少跑了一拍(实际 " + + std::to_string(ticks.load()) + ")"); + check(s.errors >= 1 && throws.load() >= 1, + "抛异常的任务被计数(errors=" + std::to_string(s.errors) + ")"); + check(s.runs >= 1, "stats().runs 有数"); + check(s.jobs == 2, "stats().jobs = 2"); +} + +} // namespace + +int main() { + std::cout << "[cron] start" << std::endl; + test_parse(); + test_match_and_next(); + test_scheduler(); + if (g_fail == 0) { + std::cout << "[cron] ALL PASS" << std::endl; + return 0; + } + std::cerr << "[cron] " << g_fail << " check(s) failed" << std::endl; + return 1; +} From 9f587478b54f15238a6c48180097b671068a74b5 Mon Sep 17 00:00:00 2001 From: zhuweiye Date: Sat, 21 Nov 2026 23:25:39 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(cron):=20=E5=85=AC=E5=BC=80=E5=A4=B4?= =?UTF-8?q?=E8=A1=A5=20UTF-8=20BOM=EF=BC=88config-contract=20=E9=97=A8?= =?UTF-8?q?=E7=A6=81=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/uvcpp/uvcpp_cron.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/uvcpp/uvcpp_cron.h b/src/uvcpp/uvcpp_cron.h index 477c0a73..3e49f326 100644 --- a/src/uvcpp/uvcpp_cron.h +++ b/src/uvcpp/uvcpp_cron.h @@ -1,4 +1,4 @@ -/** +/** * @file src/uvcpp/uvcpp_cron.h * @brief 定时任务:cron 表达式解析 + 挂在 `uvcpp_loop` 上的调度器。 * @author zhuweiye From 81f25ef8b972585ea390a0ad2064441bf181889e Mon Sep 17 00:00:00 2001 From: zhuweiye Date: Sun, 22 Nov 2026 00:30:08 +0800 Subject: [PATCH 3/3] =?UTF-8?q?test(cron):=20=E6=94=B6=E5=B0=BE=E6=94=B9?= =?UTF-8?q?=E7=94=A8=20UV=5FRUN=5FONCE=20+=20=E6=88=AA=E6=AD=A2=E6=97=B6?= =?UTF-8?q?=E9=97=B4=EF=BC=88CI=20=E4=B8=8A=E5=AE=9A=E6=97=B6=E5=99=A8=20s?= =?UTF-8?q?top=20=E5=81=B6=E5=8F=91=E4=B8=8D=E9=80=80=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/functional/cron_func.cpp | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/tests/functional/cron_func.cpp b/tests/functional/cron_func.cpp index 9d9fc074..068af157 100644 --- a/tests/functional/cron_func.cpp +++ b/tests/functional/cron_func.cpp @@ -19,7 +19,6 @@ #include #include #include -#include #include #include @@ -125,12 +124,8 @@ void test_match_and_next() { void test_scheduler() { std::cout << "-- 调度(真循环)--" << std::endl; - uvcpp_loop loop; - uvcpp_timer stopper(&loop); - // 3 秒后停循环(在循环线程上拨 stop,避免跨线程调 uv_stop)。 - stopper.start([&loop](uvcpp_timer*) { loop.stop(); }, 3000, 0); - - uvcpp_cron cron(&loop); + uvcpp_loop loop; + uvcpp_cron cron(&loop); std::atomic ticks(0); std::atomic throws(0); std::string err; @@ -146,8 +141,14 @@ void test_scheduler() { check(cron.size() == 2, "任务数 = 2"); cron.start(); - std::thread th([&loop] { loop.run(); }); - th.join(); + // **不用"定时器到点 stop"来收尾**:CI 上那种写法在 uv_run 默认模式里偶发 + // 退不出来(30s 测试超时;本机不复现)。改成主线程按截止时间拨 `UV_RUN_ONCE`: + // 每次至少处理一个事件(cron 的秒级任务保证有事件),3 秒后自己退出。 + const std::chrono::steady_clock::time_point deadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(3000); + while (std::chrono::steady_clock::now() < deadline) { + loop.run(UV_RUN_ONCE); + } cron.stop(); const uvcpp_cron_stats s = cron.stats();