fix(cron): prevent spin loop when job completes within firing second (#17821)

When a cron job fires at 13:00:00.014 and completes at 13:00:00.021,
computeNextRunAtMs was flooring nowMs to 13:00:00.000 and asking croner
for the next occurrence from that exact boundary. Croner could return
13:00:00.000 (same second) since it uses >= semantics, causing the job
to be immediately re-triggered hundreds of times.

Fix: Ask croner for the next occurrence starting from the NEXT second
(e.g., 13:00:01.000). This ensures we always skip the current/elapsed
second and correctly return the next day's occurrence.

This also correctly handles the before-match case: if nowMs is
11:59:59.500, we ask from 12:00:00.000, and croner returns today's
12:00:00.000 match.

Added regression tests for the spin loop scenario.
This commit is contained in:
Operative-001
2026-02-16 11:31:41 +01:00
committed by Peter Steinberger
parent 531f735c8a
commit de6cc05e7e
2 changed files with 32 additions and 10 deletions

View File

@@ -66,5 +66,23 @@ describe("cron schedule", () => {
const next = computeNextRunAtMs(dailyNoon, noonMs - 500);
expect(next).toBe(noonMs);
});
it("advances to next day when job completes within same second it fired (#17821)", () => {
// Regression test for #17821: cron jobs that fire and complete within
// the same second (e.g., fire at 12:00:00.014, complete at 12:00:00.021)
// were getting nextRunAtMs set to the same second, causing a spin loop.
//
// Simulating: job scheduled for 12:00:00, fires at .014, completes at .021
const completedAtMs = noonMs + 21; // 12:00:00.021
const next = computeNextRunAtMs(dailyNoon, completedAtMs);
expect(next).toBe(noonMs + 86_400_000); // must be next day, NOT noonMs
});
it("advances to next day when job completes just before second boundary (#17821)", () => {
// Edge case: job completes at .999, still within the firing second
const completedAtMs = noonMs + 999; // 12:00:00.999
const next = computeNextRunAtMs(dailyNoon, completedAtMs);
expect(next).toBe(noonMs + 86_400_000); // next day
});
});
});