From 3c8e3744c773675f1725c91d429aa063df2ddda6 Mon Sep 17 00:00:00 2001 From: NefelibateLG <3453510037@qq.com> Date: Thu, 26 Nov 2026 17:31:20 +0800 Subject: [PATCH] Preserve cron deadlines after timer overruns A cron timerfd read can consume multiple expirations. Advance the stored deadline by the number of expirations consumed so restarting the watcher does not re-arm a deadline that was already handled. Extend cronstart to cover two elapsed deadlines and check that the restarted watcher keeps its next deadline. Signed-off-by: NefelibateLG <3453510037@qq.com> --- src/uev.c | 5 +++-- test/cronstart.c | 38 +++++++++++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/uev.c b/src/uev.c index 6fb4733..6eeedc3 100644 --- a/src/uev.c +++ b/src/uev.c @@ -417,12 +417,13 @@ int uev_run(uev_ctx_t *ctx, int flags) uev_cron_stop(w); events = UEV_ERROR; } + } else if (w->u.c.interval) { + /* Keep the deadline used by uev_cron_start(). */ + w->u.c.when += exp * w->u.c.interval; } if (!w->u.c.interval) uev_timer_stop(w); - else - w->u.c.when += w->u.c.interval; break; case UEV_EVENT_TYPE: diff --git a/test/cronstart.c b/test/cronstart.c index b1b253b..3746ae0 100644 --- a/test/cronstart.c +++ b/test/cronstart.c @@ -1,6 +1,38 @@ /* Verifies that a stopped cron watcher can be started again */ #include "check.h" +static void count(uev_t *w, void *arg, int events) +{ + int *fired = arg; + + fail_unless(events == UEV_READ); + (*fired)++; +} + +static void restart_after_overrun(void) +{ + const time_t interval = 3600; + time_t when = time(NULL) - interval - interval / 2; + uev_ctx_t ctx; + uev_t cron; + int fired = 0; + + fail_unless(uev_init(&ctx) == 0); + /* Two hourly deadlines have passed before the first read. */ + fail_unless(uev_cron_init(&ctx, &cron, count, &fired, when, interval) == 0); + alarm(2); + fail_unless(uev_run(&ctx, UEV_ONCE) == 0); + alarm(0); + fail_unless(fired == 1); + fail_unless(cron.u.c.when == when + 2 * interval); + + fail_unless(uev_cron_stop(&cron) == 0); + fail_unless(uev_cron_start(&cron) == 0); + fail_unless(uev_run(&ctx, UEV_ONCE | UEV_NONBLOCK) == 0); + fail_unless(fired == 1); + fail_unless(uev_exit(&ctx) == 0); +} + int main(void) { time_t when = time(NULL) + 3600; @@ -18,7 +50,11 @@ int main(void) fail_unless(cron.u.c.when == when); fail_unless(cron.u.c.interval == 3600); - return uev_exit(&ctx); + fail_unless(uev_exit(&ctx) == 0); + + restart_after_overrun(); + + return 0; } /**