From 6b0b81492ccff7f5ac6418fc25725f5f56881fa5 Mon Sep 17 00:00:00 2001 From: Alistair Smith Date: Mon, 30 Mar 2026 20:16:02 -0700 Subject: [PATCH 01/58] Implement in-process callback-style Bun.cron (#7004) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a new overload to Bun.cron that accepts a callback as the third argument, running it in-process on the event loop at cron-scheduled intervals: const job = Bun.cron('cleanup', '*/5 * * * *', async () => { await cleanupTempFiles(); }); job.stop(); // cancel job.unref(); // don't keep process alive This complements the existing OS-level Bun.cron (crontab/launchd/ schtasks) with a lighter in-process option similar to Deno.cron. The overload is dispatched on typeof args[2] === 'function'. Key behaviors: - Next execution scheduled only after callback completes (including any returned Promise) — no overlapping invocations - Callback errors are printed but don't crash the process or stop the cron - Calling again with the same name replaces the old job, so --hot reload works without leaking timers - Reuses the existing CronExpression parser and EventLoopTimer heap Fixes #7004 --- packages/bun-types/bun.d.ts | 50 ++++ src/bun.js/api.zig | 1 + src/bun.js/api/Timer/EventLoopTimer.zig | 6 + src/bun.js/api/cron.classes.ts | 35 +++ src/bun.js/api/cron.zig | 260 ++++++++++++++++++ src/bun.js/bindings/ZigGlobalObject.cpp | 4 + src/bun.js/bindings/ZigGlobalObject.h | 2 + .../bindings/generated_classes_list.zig | 1 + src/bun.js/bindings/headers.h | 2 + test/js/bun/cron/in-process-cron.test.ts | 240 ++++++++++++++++ 10 files changed, 601 insertions(+) create mode 100644 src/bun.js/api/cron.classes.ts create mode 100644 test/js/bun/cron/in-process-cron.test.ts diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index f29ae5be59ed..e2527c040a54 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7422,7 +7422,57 @@ declare module "bun" { * await Bun.cron("./cleanup.ts", "@daily", "daily-cleanup"); * ``` */ + /** + * A handle to an in-process cron job returned by {@link Bun.cron} when called with a callback. + * + * @example + * ```ts + * const job = Bun.cron("cleanup", "0 * * * *", async () => { + * await cleanupTempFiles(); + * }); + * // Later: + * job.stop(); + * ``` + */ + interface CronJob { + /** The name this job was registered with. */ + readonly name: string; + /** The cron expression string. */ + readonly cron: string; + /** Cancel this cron job. The callback will not fire again. */ + stop(): CronJob; + /** Keep the process alive while this job is scheduled (default). */ + ref(): CronJob; + /** Allow the process to exit even while this job is scheduled. */ + unref(): CronJob; + } + const cron: { + /** + * Schedule an in-process cron job that calls a function on a schedule. + * + * The callback is invoked on the event loop. The next execution is scheduled + * only after the callback (including any returned Promise) completes, so + * invocations never overlap. If the callback throws or rejects, the error is + * reported as an uncaught exception but the job continues running. + * + * Calling again with the same name replaces the previous job, which makes + * `--hot` reload work without leaking timers. + * + * @param name - Unique name for this job (used for replacement) + * @param schedule - Cron expression or nickname (e.g. `"*/5 * * * *"`, `"@hourly"`) + * @param handler - Function to call on schedule. May be async. + * @returns A {@link CronJob} handle with `stop()`, `ref()`, `unref()` + * + * @example + * ```ts + * const job = Bun.cron("cleanup", "0 * * * *", async () => { + * await cleanupTempFiles(); + * }); + * // Later: job.stop() + * ``` + */ + (name: string, schedule: CronWithAutocomplete, handler: () => void | Promise): CronJob; (path: string, schedule: CronWithAutocomplete, title: string): Promise; /** * Remove a previously registered cron job by its title. diff --git a/src/bun.js/api.zig b/src/bun.js/api.zig index 534ccb19d9b0..3079155ee3a5 100644 --- a/src/bun.js/api.zig +++ b/src/bun.js/api.zig @@ -25,6 +25,7 @@ pub const TLSSocket = @import("./api/bun/socket.zig").TLSSocket; pub const SocketHandlers = @import("./api/bun/socket.zig").Handlers; pub const Subprocess = @import("./api/bun/subprocess.zig"); +pub const cron = @import("./api/cron.zig"); pub const Terminal = @import("./api/bun/Terminal.zig"); pub const WebViewHostProcess = @import("./webview/HostProcess.zig"); pub const ChromeProcess = @import("./webview/ChromeProcess.zig"); diff --git a/src/bun.js/api/Timer/EventLoopTimer.zig b/src/bun.js/api/Timer/EventLoopTimer.zig index 8a376fc65efc..680f69cd92d9 100644 --- a/src/bun.js/api/Timer/EventLoopTimer.zig +++ b/src/bun.js/api/Timer/EventLoopTimer.zig @@ -70,6 +70,7 @@ pub const Tag = enum { DateHeaderTimer, BunTest, EventLoopDelayMonitor, + CronJob, pub fn Type(comptime T: Tag) type { return switch (T) { @@ -95,6 +96,7 @@ pub const Tag = enum { .DateHeaderTimer => jsc.API.Timer.DateHeaderTimer, .BunTest => jsc.Jest.bun_test.BunTest, .EventLoopDelayMonitor => jsc.API.Timer.EventLoopDelayMonitor, + .CronJob => bun.api.cron.CronJob, }; } @@ -191,6 +193,10 @@ pub fn fire(self: *Self, now: *const timespec, vm: *VirtualMachine) void { const monitor = @as(*jsc.API.Timer.EventLoopDelayMonitor, @fieldParentPtr("event_loop_timer", self)); monitor.onFire(vm, now); }, + .CronJob => { + const job = @as(*bun.api.cron.CronJob, @fieldParentPtr("event_loop_timer", self)); + job.onTimerFire(vm); + }, inline else => |t| { if (@FieldType(t.Type(), "event_loop_timer") != Self) { @compileError(@typeName(t.Type()) ++ " has wrong type for 'event_loop_timer'"); diff --git a/src/bun.js/api/cron.classes.ts b/src/bun.js/api/cron.classes.ts new file mode 100644 index 000000000000..4aceff29a8a3 --- /dev/null +++ b/src/bun.js/api/cron.classes.ts @@ -0,0 +1,35 @@ +import { define } from "../../codegen/class-definitions"; + +export default [ + define({ + name: "CronJob", + construct: false, + noConstructor: true, + finalize: true, + configurable: false, + klass: {}, + JSType: "0b11101110", + proto: { + stop: { + fn: "stop", + length: 0, + }, + ref: { + fn: "doRef", + length: 0, + }, + unref: { + fn: "doUnref", + length: 0, + }, + name: { + getter: "getName", + cache: true, + }, + cron: { + getter: "getCron", + cache: true, + }, + }, + }), +]; diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 9a3c5e70ecc5..e3d512ceeb3f 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -413,6 +413,10 @@ pub const CronRegisterJob = struct { pub fn cronRegister(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args = callframe.argumentsAsArray(3); + // In-process callback cron: Bun.cron(name, schedule, handler) + if (args[2].isCallable()) + return CronJob.register(globalObject, args[0], args[1], args[2]); + if (!args[0].isString()) return globalObject.throwInvalidArguments("Bun.cron() expects a string path as the first argument", .{}); if (!args[1].isString()) return globalObject.throwInvalidArguments("Bun.cron() expects a string schedule as the second argument", .{}); if (!args[2].isString()) return globalObject.throwInvalidArguments("Bun.cron() expects a string title as the third argument", .{}); @@ -804,6 +808,261 @@ pub const CronRemoveJob = struct { } }; +// ============================================================================ +// CronJob — in-process callback-style cron (issue #7004) +// ============================================================================ +// +// Bun.cron(name, "*/5 * * * *", async () => { ... }) +// +// Unlike the OS-level cron above, this runs the callback in the current +// process on the event loop. The next execution is scheduled only after the +// callback (including any returned Promise) completes, so callbacks never +// overlap. Calling Bun.cron() again with the same name replaces the old job, +// which makes --hot reload work without leaking timers. + +pub const CronJob = struct { + pub const js = jsc.Codegen.JSCronJob; + pub const toJS = js.toJS; + pub const fromJS = js.fromJS; + pub const fromJSDirect = js.fromJSDirect; + + event_loop_timer: EventLoopTimer = .{ .tag = .CronJob, .next = .epoch }, + callback: jsc.Strong.Optional = .empty, + global: *jsc.JSGlobalObject, + parsed: CronExpression, + name: []const u8, + expression: []const u8, + poll: bun.Async.KeepAlive = .{}, + this_value: jsc.JSRef = jsc.JSRef.empty(), + #ref_count: u32 = 1, + stopped: bool = false, + has_js_ref: bool = true, + + pub const new = bun.TrivialNew(@This()); + + var jobs_map: std.StringHashMapUnmanaged(*CronJob) = .{}; + + fn ref(this: *CronJob) void { + this.#ref_count += 1; + } + + fn deref(this: *CronJob) void { + this.#ref_count -= 1; + if (this.#ref_count == 0) { + this.deinit(); + bun.destroy(this); + } + } + + fn deinit(this: *CronJob) void { + this.callback.deinit(); + this.this_value.deinit(); + bun.default_allocator.free(this.name); + bun.default_allocator.free(this.expression); + } + + pub fn finalize(this: *CronJob) void { + this.this_value = .{ .finalized = {} }; + this.deref(); + } + + fn computeNextTimespec(this: *CronJob) ?bun.timespec { + const now_ms: f64 = @floatFromInt(std.time.milliTimestamp()); + const next_ms = (this.parsed.next(this.global, now_ms) catch return null) orelse return null; + const delta: i64 = @intFromFloat(@max(1.0, next_ms - now_ms)); + return bun.timespec.msFromNow(.allow_mocked_time, delta); + } + + fn scheduleNext(this: *CronJob, vm: *jsc.VirtualMachine) void { + if (this.stopped) { + this.cleanupAfterStop(vm); + return; + } + const next_time = this.computeNextTimespec() orelse { + this.stopped = true; + this.cleanupAfterStop(vm); + return; + }; + vm.timer.update(&this.event_loop_timer, &next_time); + } + + fn cleanupAfterStop(this: *CronJob, vm: *jsc.VirtualMachine) void { + this.poll.unref(vm); + if (this.this_value != .finalized) + this.this_value.downgrade(); + } + + pub fn onTimerFire(this: *CronJob, vm: *jsc.VirtualMachine) void { + this.event_loop_timer.state = .FIRED; + + if (this.stopped or vm.scriptExecutionStatus() != .running) { + this.cleanupAfterStop(vm); + return; + } + + const cb = this.callback.get() orelse { + this.stopped = true; + this.cleanupAfterStop(vm); + return; + }; + + vm.eventLoop().enter(); + defer vm.eventLoop().exit(); + + const result = cb.call(this.global, .js_undefined, &.{}) catch { + if (this.global.tryTakeException()) |err| + vm.runErrorHandler(err, null); + this.scheduleNext(vm); + return; + }; + + if (result.asAnyPromise()) |promise| { + switch (promise.status()) { + .pending => { + this.ref(); + result.then(this.global, this, onPromiseResolve, onPromiseReject) catch { + this.deref(); + this.scheduleNext(vm); + }; + return; + }, + .fulfilled => {}, + .rejected => { + promise.setHandled(this.global.vm()); + vm.runErrorHandler(promise.result(this.global.vm()), null); + }, + } + } + + this.scheduleNext(vm); + } + + pub export const Bun__CronJob__onPromiseResolve = jsc.toJSHostFn(onPromiseResolve); + pub export const Bun__CronJob__onPromiseReject = jsc.toJSHostFn(onPromiseReject); + + fn onPromiseResolve(_: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + const args = callframe.arguments(); + var this: *CronJob = args[args.len - 1].asPromisePtr(CronJob); + defer this.deref(); + this.scheduleNext(this.global.bunVM()); + return .js_undefined; + } + + fn onPromiseReject(_: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + const args = callframe.arguments(); + var this: *CronJob = args[args.len - 1].asPromisePtr(CronJob); + defer this.deref(); + const vm = this.global.bunVM(); + const err = if (args.len > 0) args[0] else .js_undefined; + vm.runErrorHandler(err, null); + this.scheduleNext(vm); + return .js_undefined; + } + + pub fn stop(this: *CronJob, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + if (this.stopped) return callframe.this(); + this.stopped = true; + + if (jobs_map.fetchRemove(this.name)) |kv| + bun.default_allocator.free(kv.key); + + const vm = this.global.bunVM(); + if (this.event_loop_timer.state == .ACTIVE) + vm.timer.remove(&this.event_loop_timer); + this.cleanupAfterStop(vm); + + return callframe.this(); + } + + pub fn doRef(this: *CronJob, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + if (!this.has_js_ref and !this.stopped) { + this.has_js_ref = true; + this.poll.ref(this.global.bunVM()); + } + return callframe.this(); + } + + pub fn doUnref(this: *CronJob, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + if (this.has_js_ref) { + this.has_js_ref = false; + this.poll.unref(this.global.bunVM()); + } + return callframe.this(); + } + + pub fn getName(this: *CronJob, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + return bun.String.createUTF8ForJS(globalObject, this.name); + } + + pub fn getCron(this: *CronJob, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + return bun.String.createUTF8ForJS(globalObject, this.expression); + } + + pub fn register(globalObject: *jsc.JSGlobalObject, name_arg: jsc.JSValue, schedule_arg: jsc.JSValue, callback_arg: jsc.JSValue) bun.JSError!jsc.JSValue { + if (!name_arg.isString()) + return globalObject.throwInvalidArguments("Bun.cron() expects a string name as the first argument", .{}); + if (!schedule_arg.isString()) + return globalObject.throwInvalidArguments("Bun.cron() expects a string cron expression as the second argument", .{}); + + const name_str = try name_arg.toBunString(globalObject); + defer name_str.deref(); + const name_slice = name_str.toUTF8(bun.default_allocator); + defer name_slice.deinit(); + + if (name_slice.slice().len == 0) + return globalObject.throwInvalidArguments("Bun.cron() name must not be empty", .{}); + + const schedule_str = try schedule_arg.toBunString(globalObject); + defer schedule_str.deref(); + const schedule_slice = schedule_str.toUTF8(bun.default_allocator); + defer schedule_slice.deinit(); + + const parsed = CronExpression.parse(schedule_slice.slice()) catch + return globalObject.throwInvalidArguments("Invalid cron expression. Expected 5 space-separated fields (minute hour day month weekday), each being *, a number, or a range/step pattern", .{}); + + // Stop any existing job with this name (makes --hot re-registration work). + if (jobs_map.fetchRemove(name_slice.slice())) |existing| { + bun.default_allocator.free(existing.key); + const old = existing.value; + if (!old.stopped) { + old.stopped = true; + const vm = globalObject.bunVM(); + if (old.event_loop_timer.state == .ACTIVE) + vm.timer.remove(&old.event_loop_timer); + old.cleanupAfterStop(vm); + } + } + + const job = CronJob.new(.{ + .global = globalObject, + .parsed = parsed, + .name = bun.handleOom(bun.default_allocator.dupe(u8, name_slice.slice())), + .expression = bun.handleOom(bun.default_allocator.dupe(u8, schedule_slice.slice())), + }); + job.callback = .create(callback_arg, globalObject); + + const next_time = job.computeNextTimespec() orelse { + job.callback.deinit(); + bun.default_allocator.free(job.name); + bun.default_allocator.free(job.expression); + bun.destroy(job); + return globalObject.throwInvalidArguments("Cron expression '{s}' has no future occurrences", .{schedule_slice.slice()}); + }; + + const js_value = job.toJS(globalObject); + job.this_value.setStrong(js_value, globalObject); + + const vm = globalObject.bunVM(); + job.poll.ref(vm); + vm.timer.update(&job.event_loop_timer, &next_time); + + const key = bun.handleOom(bun.default_allocator.dupe(u8, name_slice.slice())); + bun.handleOom(jobs_map.put(bun.default_allocator, key, job)); + + return js_value; + } +}; + // ============================================================================ // Bun.cron object builder // ============================================================================ @@ -1463,3 +1722,4 @@ const bun = @import("bun"); const jsc = bun.jsc; const OutputReader = bun.io.BufferedReader; const Process = bun.spawn.Process; +const EventLoopTimer = bun.api.Timer.EventLoopTimer; diff --git a/src/bun.js/bindings/ZigGlobalObject.cpp b/src/bun.js/bindings/ZigGlobalObject.cpp index 17fb09f4ba05..23d64c6ab5b0 100644 --- a/src/bun.js/bindings/ZigGlobalObject.cpp +++ b/src/bun.js/bindings/ZigGlobalObject.cpp @@ -3545,6 +3545,10 @@ GlobalObject::PromiseFunctions GlobalObject::promiseHandlerID(Zig::FFIFunction h return GlobalObject::PromiseFunctions::Bun__FileSink__onResolveStream; } else if (handler == Bun__FileSink__onRejectStream) { return GlobalObject::PromiseFunctions::Bun__FileSink__onRejectStream; + } else if (handler == Bun__CronJob__onPromiseResolve) { + return GlobalObject::PromiseFunctions::Bun__CronJob__onPromiseResolve; + } else if (handler == Bun__CronJob__onPromiseReject) { + return GlobalObject::PromiseFunctions::Bun__CronJob__onPromiseReject; } else { RELEASE_ASSERT_NOT_REACHED(); } diff --git a/src/bun.js/bindings/ZigGlobalObject.h b/src/bun.js/bindings/ZigGlobalObject.h index 5ec1745efdc3..e92ab9565b9a 100644 --- a/src/bun.js/bindings/ZigGlobalObject.h +++ b/src/bun.js/bindings/ZigGlobalObject.h @@ -394,6 +394,8 @@ class GlobalObject : public Bun::GlobalScope { Bun__FileStreamWrapper__onResolveRequestStream, Bun__FileSink__onResolveStream, Bun__FileSink__onRejectStream, + Bun__CronJob__onPromiseResolve, + Bun__CronJob__onPromiseReject, }; static constexpr size_t promiseFunctionsSize = 36; diff --git a/src/bun.js/bindings/generated_classes_list.zig b/src/bun.js/bindings/generated_classes_list.zig index 84e1839b67b4..bf43edaa1b34 100644 --- a/src/bun.js/bindings/generated_classes_list.zig +++ b/src/bun.js/bindings/generated_classes_list.zig @@ -49,6 +49,7 @@ pub const Classes = struct { pub const ServerWebSocket = api.ServerWebSocket; pub const Subprocess = api.Subprocess; pub const ResourceUsage = api.Subprocess.ResourceUsage; + pub const CronJob = api.cron.CronJob; pub const Terminal = api.Terminal; pub const TCPSocket = api.TCPSocket; pub const TLSSocket = api.TLSSocket; diff --git a/src/bun.js/bindings/headers.h b/src/bun.js/bindings/headers.h index f6bcbd4af02e..7181edae3774 100644 --- a/src/bun.js/bindings/headers.h +++ b/src/bun.js/bindings/headers.h @@ -754,6 +754,8 @@ BUN_DECLARE_HOST_FUNCTION(Bun__BodyValueBufferer__onResolveStream); BUN_DECLARE_HOST_FUNCTION(Bun__TestScope__Describe2__bunTestThen); BUN_DECLARE_HOST_FUNCTION(Bun__TestScope__Describe2__bunTestCatch); +BUN_DECLARE_HOST_FUNCTION(Bun__CronJob__onPromiseResolve); +BUN_DECLARE_HOST_FUNCTION(Bun__CronJob__onPromiseReject); #endif diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts new file mode 100644 index 000000000000..87b9acb5a930 --- /dev/null +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -0,0 +1,240 @@ +import { test, expect, describe } from "bun:test"; +import { bunEnv, bunExe, normalizeBunSnapshot } from "harness"; + +describe("Bun.cron (in-process)", () => { + test("validates cron expression", () => { + expect(() => Bun.cron("x", "invalid expr", () => {})).toThrow(/Invalid cron expression/); + expect(() => Bun.cron("x", "* * * *", () => {})).toThrow(/Invalid cron expression/); + expect(() => Bun.cron("x", "60 * * * *", () => {})).toThrow(/Invalid cron expression/); + }); + + test("validates name is non-empty string", () => { + expect(() => Bun.cron("", "* * * * *", () => {})).toThrow(/name must not be empty/); + // @ts-expect-error + expect(() => Bun.cron(123, "* * * * *", () => {})).toThrow(/string name/); + }); + + test("rejects expressions with no future occurrences", () => { + // Feb 30 never exists + expect(() => Bun.cron("x", "0 0 30 2 *", () => {})).toThrow(/no future occurrences/); + }); + + test("returns CronJob with name and cron getters", () => { + const job = Bun.cron("test-getters", "* * * * *", () => {}); + try { + expect(job.name).toBe("test-getters"); + expect(job.cron).toBe("* * * * *"); + } finally { + job.stop(); + } + }); + + test("stop() cancels before first fire", () => { + let called = false; + const job = Bun.cron("test-stop", "* * * * *", () => { + called = true; + }); + job.stop(); + // stop() returns immediately; callback was never scheduled to run + expect(called).toBe(false); + }); + + test("stop() is idempotent", () => { + const job = Bun.cron("test-stop-idem", "* * * * *", () => {}); + expect(() => { + job.stop(); + job.stop(); + job.stop(); + }).not.toThrow(); + }); + + test("ref()/unref() are chainable", () => { + const job = Bun.cron("test-chain", "* * * * *", () => {}); + try { + expect(job.unref()).toBe(job); + expect(job.ref()).toBe(job); + expect(job.stop()).toBe(job); + } finally { + job.stop(); + } + }); + + test("same name replaces previous job", () => { + let calls1 = 0; + let calls2 = 0; + const job1 = Bun.cron("replace-test", "* * * * *", () => { + calls1++; + }); + // Registering again with same name should stop job1 + const job2 = Bun.cron("replace-test", "* * * * *", () => { + calls2++; + }); + try { + // Both handles exist but only job2 is active + expect(job1.name).toBe("replace-test"); + expect(job2.name).toBe("replace-test"); + // Stopping job2 is what matters now; job1 was already stopped by replacement + job1.stop(); // no-op, already stopped + job2.stop(); + } finally { + job2.stop(); + } + expect(calls1).toBe(0); + expect(calls2).toBe(0); + }); + + test("accepts @nicknames", () => { + const job = Bun.cron("test-nickname", "@hourly", () => {}); + try { + expect(job.cron).toBe("@hourly"); + } finally { + job.stop(); + } + }); + + test("supports named weekdays and months", () => { + const job = Bun.cron("test-names", "0 9 * JAN-DEC MON-FRI", () => {}); + try { + expect(job.cron).toBe("0 9 * JAN-DEC MON-FRI"); + } finally { + job.stop(); + } + }); + + test("keeps process alive by default; unref() allows exit", async () => { + // ref'd: process stays alive (would block forever), so we spawn with timeout via cron + // unref'd: process exits immediately + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + const job = Bun.cron("x", "* * * * *", () => {}); + job.unref(); + console.log("scheduled"); + `, + ], + env: bunEnv, + stderr: "pipe", + }); + const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(normalizeBunSnapshot(stdout)).toBe("scheduled"); + expect(exitCode).toBe(0); + }); + + test("ref'd job prevents process exit", async () => { + // The cron keeps the loop alive; we stop it after a short delay to let the process exit. + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + const job = Bun.cron("x", "* * * * *", () => {}); + console.log("scheduled"); + setTimeout(() => { job.stop(); console.log("stopped"); }, 50); + `, + ], + env: bunEnv, + stderr: "pipe", + }); + const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(normalizeBunSnapshot(stdout)).toBe("scheduled\nstopped"); + expect(exitCode).toBe(0); + }); + + test("distinguishes callback overload from OS-level overload", () => { + // Callable 3rd arg → in-process; string 3rd arg → OS-level. + // We only verify the callback path here; the string path is covered elsewhere. + const job = Bun.cron("overload-test", "* * * * *", () => {}); + try { + // CronJob has stop(); Promise would not + expect(typeof job.stop).toBe("function"); + expect(job).not.toBeInstanceOf(Promise); + } finally { + job.stop(); + } + }); +}); + +describe.concurrent("Bun.cron (in-process) — firing", () => { + // This test waits for a real cron fire, which takes up to 60 seconds. + // The cron expression "* * * * *" fires at the top of every minute. + test("callback fires at minute boundary", async () => { + let fired = 0; + let resolve: () => void; + const promise = new Promise(r => { + resolve = r; + }); + + const job = Bun.cron("fire-test", "* * * * *", () => { + fired++; + resolve!(); + }); + + try { + await promise; + expect(fired).toBe(1); + } finally { + job.stop(); + } + }, 70_000); + + test("async callback delays next scheduling", async () => { + // The callback returns a Promise; next fire is scheduled only after it resolves. + // We can't easily observe the timing without waiting 2+ minutes, so we just + // verify no crash and that stop() during the pending promise works. + let resolveHandler: () => void; + const handlerPromise = new Promise(r => { + resolveHandler = r; + }); + let fireResolve: () => void; + const firePromise = new Promise(r => { + fireResolve = r; + }); + + const job = Bun.cron("async-test", "* * * * *", async () => { + fireResolve!(); + await handlerPromise; + }); + + try { + await firePromise; + // Handler is now awaiting; stop while it's pending + job.stop(); + // Let the handler complete + resolveHandler!(); + await Bun.sleep(10); + // No crash, no second fire + } finally { + job.stop(); + } + }, 70_000); + + test("error in callback is reported but cron continues", async () => { + // Spawn a subprocess so we can observe the uncaught exception on stderr + // and verify the process doesn't crash. + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + let fires = 0; + const job = Bun.cron("err-test", "* * * * *", () => { + fires++; + if (fires === 1) { + // Stop after second scheduling — the error doesn't kill us + setTimeout(() => { job.stop(); console.log("fires=" + fires); }, 100); + throw new Error("boom"); + } + }); + `, + ], + env: bunEnv, + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stdout.trim()).toBe("fires=1"); + expect(stderr).toContain("boom"); + expect(exitCode).toBe(0); + }, 70_000); +}); From 6a64dbcbdb4a2331aa7e607cfd9fc640b3358826 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Tue, 31 Mar 2026 03:18:01 +0000 Subject: [PATCH 02/58] [autofix.ci] apply automated fixes --- test/js/bun/cron/in-process-cron.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index 87b9acb5a930..ce0f0b22cda3 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -1,4 +1,4 @@ -import { test, expect, describe } from "bun:test"; +import { describe, expect, test } from "bun:test"; import { bunEnv, bunExe, normalizeBunSnapshot } from "harness"; describe("Bun.cron (in-process)", () => { From be14e0992739ef830cecf8b25afad2b06694cf26 Mon Sep 17 00:00:00 2001 From: Alistair Smith Date: Mon, 30 Mar 2026 20:32:45 -0700 Subject: [PATCH 03/58] =?UTF-8?q?Fix=20JSDoc=20comment=20=E2=80=94=20escap?= =?UTF-8?q?e=20*/=20in=20cron=20expression=20example?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/bun-types/bun.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index e2527c040a54..1ceb61cef276 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7460,7 +7460,7 @@ declare module "bun" { * `--hot` reload work without leaking timers. * * @param name - Unique name for this job (used for replacement) - * @param schedule - Cron expression or nickname (e.g. `"*/5 * * * *"`, `"@hourly"`) + * @param schedule - Cron expression or nickname (e.g. `"*\/5 * * * *"`, `"@hourly"`) * @param handler - Function to call on schedule. May be async. * @returns A {@link CronJob} handle with `stop()`, `ref()`, `unref()` * From 436a4d593494862e15d949988a6e5ef17d541494 Mon Sep 17 00:00:00 2001 From: Alistair Smith Date: Mon, 30 Mar 2026 21:13:10 -0700 Subject: [PATCH 04/58] Match setTimeout error semantics for cron callbacks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sync throws from cron callbacks now emit uncaughtException (fatal by default), and rejected Promises emit unhandledRejection — identical to setTimeout behavior. Users who want resilient crons install the same process.on handlers they'd use for setInterval. Previously errors were silently printed to stderr without going through the event machinery, which meant error reporting tools (Sentry, etc.) would never see cron failures. Error reporting goes through vm.global (not the stored this.global) to match what TimerObjectInternals does. --- packages/bun-types/bun.d.ts | 214 +++++++++++++++++------ src/bun.js/api/cron.zig | 12 +- test/js/bun/cron/in-process-cron.test.ts | 64 +++++-- 3 files changed, 218 insertions(+), 72 deletions(-) diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index 1ceb61cef276..06db95f4b80a 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7381,47 +7381,6 @@ declare module "bun" { | `${string} ${string} ${string} ${string} ${string}` | (string & {}); - /** - * Register an OS-level cron job that runs a JavaScript/TypeScript module on a schedule. - * - * The module must export a `default` object with a `scheduled(controller)` method, - * conforming to the [Cloudflare Workers Cron Triggers API](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/). - * - * On Linux, registers with [crontab](https://man7.org/linux/man-pages/man5/crontab.5.html). - * On macOS, registers with [launchd](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html). - * On Windows, registers with [Task Scheduler](https://learn.microsoft.com/en-us/windows/win32/taskschd/task-scheduler-start-page). - * - * **Cron expression syntax** (5 fields: `minute hour day month weekday`): - * - * | Field | Values | Special | - * |-------|--------|---------| - * | Minute | `0-59` | `*` `,` `-` `/` | - * | Hour | `0-23` | `*` `,` `-` `/` | - * | Day of month | `1-31` | `*` `,` `-` `/` | - * | Month | `1-12` or `JAN-DEC` | `*` `,` `-` `/` | - * | Day of week | `0-7` or `SUN-SAT` | `*` `,` `-` `/` | - * - * - `0` and `7` both mean Sunday in the weekday field. - * - Month/day names are case-insensitive (`MON`, `Mon`, `Monday` all work). - * - Predefined nicknames: `@yearly`, `@annually`, `@monthly`, `@weekly`, `@daily`, `@midnight`, `@hourly`. - * - When both day-of-month and day-of-week are specified (neither is `*`), - * the job runs when **either** field matches ([POSIX cron](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html) behavior). - * - * @param path - Path to the script to run (resolved relative to caller) - * @param schedule - Cron expression or predefined nickname (e.g. `"30 2 * * MON"`, `"@daily"`) - * @param title - Unique identifier for this cron job (alphanumeric, hyphens, underscores only) - * @returns Promise that resolves when the cron job is registered - * @throws If the expression is invalid, the title contains invalid characters, or registration fails - * - * @example - * ```ts - * // Run every Monday at 2:30 AM - * await Bun.cron("./worker.ts", "30 2 * * MON", "weekly-report"); - * - * // Run daily at midnight - * await Bun.cron("./cleanup.ts", "@daily", "daily-cleanup"); - * ``` - */ /** * A handle to an in-process cron job returned by {@link Bun.cron} when called with a callback. * @@ -7449,30 +7408,177 @@ declare module "bun" { const cron: { /** - * Schedule an in-process cron job that calls a function on a schedule. + * Schedule an **in-process** cron job that calls a function on a schedule. + * + * Unlike the module-path overload, this runs the callback on the current event loop — + * the job dies with the process and does not survive reboots. State is shared between + * invocations (closures, module-level variables, database connections all persist). * - * The callback is invoked on the event loop. The next execution is scheduled - * only after the callback (including any returned Promise) completes, so - * invocations never overlap. If the callback throws or rejects, the error is - * reported as an uncaught exception but the job continues running. + * | | In-process (this overload) | OS-level (path + title) | + * |---|---|---| + * | Survives process exit | No | Yes | + * | Shared state between runs | Yes | No (fresh process each time) | + * | Windows expression limits | None | 48-trigger cap | + * | Return type | {@link CronJob} (sync) | `Promise` | * - * Calling again with the same name replaces the previous job, which makes - * `--hot` reload work without leaking timers. + * ### No-overlap guarantee * - * @param name - Unique name for this job (used for replacement) - * @param schedule - Cron expression or nickname (e.g. `"*\/5 * * * *"`, `"@hourly"`) - * @param handler - Function to call on schedule. May be async. - * @returns A {@link CronJob} handle with `stop()`, `ref()`, `unref()` + * The next fire time is computed only after the callback settles (including any returned + * Promise). If your callback takes 3 minutes and runs every minute, it fires at T+0 → runs + * until T+3 → next fire is the first minute boundary after T+3. Invocations never stack. + * + * ### Error semantics + * + * Matches `setTimeout`: a synchronous throw emits `uncaughtException`, a rejected Promise + * emits `unhandledRejection`. Without a listener, the process exits with code 1. The job + * reschedules itself after an error — it does not stop on first failure. + * + * ```ts + * process.on("unhandledRejection", (err) => log.error(err)); // keep going + * Bun.cron("flaky", "* * * * *", async () => { await mightThrow(); }); + * ``` + * + * ### Cron expression syntax + * + * Five fields: `minute hour day-of-month month day-of-week`. + * + * | Field | Values | Special chars | + * |-------|--------|---------------| + * | Minute | `0-59` | `*` `,` `-` `/` | + * | Hour | `0-23` | `*` `,` `-` `/` | + * | Day of month | `1-31` | `*` `,` `-` `/` | + * | Month | `1-12` or `JAN`-`DEC` | `*` `,` `-` `/` | + * | Day of week | `0-7` or `SUN`-`SAT` | `*` `,` `-` `/` | + * + * - `0` and `7` both mean Sunday. + * - Month and weekday names are case-insensitive 3-letter abbreviations. + * - Nicknames: `@yearly`, `@annually`, `@monthly`, `@weekly`, `@daily`, `@midnight`, `@hourly`. + * - When both day-of-month and day-of-week are restricted (neither is `*`), the job + * fires when **either** matches — [POSIX cron](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html) OR semantics. + * - All expressions work on all platforms — there is no Windows trigger limit here. + * + * ### Lifecycle & `--hot` + * + * Calling `Bun.cron()` again with the same `name` stops the previous job and replaces it, + * so top-level `Bun.cron()` calls are safe under `bun --hot` — reloading your module won't + * leak timers. By default the job keeps the process alive (like `setInterval`); call + * `.unref()` to let the process exit naturally when nothing else is pending. + * + * @param name Unique identifier for this job. Registering the same name again replaces + * the previous job. Not written to the OS — purely for in-process bookkeeping. + * @param schedule Cron expression or nickname (e.g. `"*\/5 * * * *"`, `"@hourly"`). + * @param handler Function to call on each fire. May return a Promise — the next fire + * is not scheduled until it settles. + * @returns A {@link CronJob} handle. Chainable: `.stop()`, `.ref()`, `.unref()` all + * return the job itself. + * @throws Synchronously if `schedule` is invalid, `name` is empty or not a string, or the + * expression has no future occurrences (e.g. `"0 0 30 2 *"` — February 30th). * * @example * ```ts - * const job = Bun.cron("cleanup", "0 * * * *", async () => { + * // Hourly cleanup, keeps process alive + * Bun.cron("cleanup", "0 * * * *", async () => { * await cleanupTempFiles(); * }); - * // Later: job.stop() + * + * // Background healthcheck that doesn't block process exit + * Bun.cron("ping", "*\/30 * * * *", () => fetch("/health")).unref(); + * + * // Stop conditionally + * const job = Bun.cron("poll", "* * * * *", async () => { + * if (await isDone()) job.stop(); + * }); * ``` + * + * @see {@link CronJob} for the returned handle. + * @see {@link Bun.cron.parse} to preview the next fire time. */ (name: string, schedule: CronWithAutocomplete, handler: () => void | Promise): CronJob; + /** + * Register an **OS-level** cron job that runs a JavaScript/TypeScript module on a schedule. + * + * Unlike the callback overload, this registers the job with the operating system's + * scheduler — the job survives process exit and persists across reboots. Bun spawns + * a fresh process for each invocation, so there is no shared state between runs. + * + * | Platform | Scheduler | Inspect with | + * |----------|-----------|--------------| + * | Linux | [crontab](https://man7.org/linux/man-pages/man5/crontab.5.html) | `crontab -l` | + * | macOS | [launchd](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html) | `launchctl list` | + * | Windows | [Task Scheduler](https://learn.microsoft.com/en-us/windows/win32/taskschd/task-scheduler-start-page) | `schtasks /query` | + * + * ### Module shape + * + * The target module must have a `default` export with a `scheduled(controller)` method, + * matching the [Cloudflare Workers Cron Triggers](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/) + * API. The controller exposes `cron` (the expression) and `scheduledTime` (ms since epoch). + * + * ```ts + * // worker.ts + * export default { + * async scheduled(controller: Bun.CronController) { + * console.log(`Fired: ${controller.cron} at ${new Date(controller.scheduledTime)}`); + * await doWork(); + * }, + * }; + * ``` + * + * ### Cron expression syntax + * + * Five fields: `minute hour day-of-month month day-of-week`. + * + * | Field | Values | Special chars | + * |-------|--------|---------------| + * | Minute | `0-59` | `*` `,` `-` `/` | + * | Hour | `0-23` | `*` `,` `-` `/` | + * | Day of month | `1-31` | `*` `,` `-` `/` | + * | Month | `1-12` or `JAN`-`DEC` | `*` `,` `-` `/` | + * | Day of week | `0-7` or `SUN`-`SAT` | `*` `,` `-` `/` | + * + * - `0` and `7` both mean Sunday. + * - Month and weekday names are case-insensitive 3-letter abbreviations. + * - Nicknames: `@yearly`, `@annually`, `@monthly`, `@weekly`, `@daily`, `@midnight`, `@hourly`. + * - When both day-of-month and day-of-week are restricted (neither is `*`), the job + * fires when **either** matches — [POSIX cron](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html) OR semantics. + * + * ### Platform caveats + * + * - **Windows:** minute steps that don't evenly divide 60 (e.g. `*\/7`, `*\/11`) with + * all hours active exceed Task Scheduler's 48-trigger limit and throw. Divisors + * of 60 (`*\/5`, `*\/10`, `*\/15`, `*\/20`, `*\/30`) and all common patterns work. + * - **Windows headless/CI:** registration fails if the current user's SID can't be + * resolved (typical under service accounts). Run as a regular user or create the + * task manually with `schtasks /create /ru SYSTEM`. + * - **macOS:** stdout/stderr are written to `/tmp/bun.cron..{stdout,stderr}.log`. + * + * ### Idempotency & removal + * + * Registering with a title that already exists replaces the previous entry. Use + * {@link Bun.cron.remove} to unregister. The title is namespaced per user, so + * different users can register jobs with the same title independently. + * + * @param path Path to the module to run. Resolved relative to the calling file. + * @param schedule Cron expression or nickname (e.g. `"30 2 * * MON"`, `"@daily"`). + * @param title Unique identifier for this job. Alphanumeric, hyphens, and underscores only — + * used directly in crontab markers, launchd service labels, and schtasks task names. + * @returns Promise that resolves once the OS scheduler has accepted the job. + * @throws If the cron expression is invalid, `title` contains illegal characters, + * the expression exceeds Windows' trigger limit, or the underlying scheduler command fails + * (the error message includes the scheduler's stderr output). + * + * @example + * ```ts + * // Register once (e.g. in a postinstall script or setup command) + * await Bun.cron("./jobs/weekly-report.ts", "30 2 * * MON", "weekly-report"); + * await Bun.cron("./jobs/cleanup.ts", "@daily", "daily-cleanup"); + * + * // Later, to unregister: + * await Bun.cron.remove("weekly-report"); + * ``` + * + * @see {@link Bun.cron.remove} to unregister. + * @see {@link Bun.cron.parse} to preview the next fire time. + */ (path: string, schedule: CronWithAutocomplete, title: string): Promise<void>; /** * Remove a previously registered cron job by its title. diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index e3d512ceeb3f..e893075e9319 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -817,8 +817,10 @@ pub const CronRemoveJob = struct { // Unlike the OS-level cron above, this runs the callback in the current // process on the event loop. The next execution is scheduled only after the // callback (including any returned Promise) completes, so callbacks never -// overlap. Calling Bun.cron() again with the same name replaces the old job, -// which makes --hot reload work without leaking timers. +// overlap. Error semantics match setTimeout: sync throws become +// uncaughtException, rejected Promises become unhandledRejection. Calling +// Bun.cron() again with the same name replaces the old job, which makes +// --hot reload work without leaking timers. pub const CronJob = struct { pub const js = jsc.Codegen.JSCronJob; @@ -911,7 +913,7 @@ pub const CronJob = struct { const result = cb.call(this.global, .js_undefined, &.{}) catch { if (this.global.tryTakeException()) |err| - vm.runErrorHandler(err, null); + _ = vm.uncaughtException(vm.global, err, false); this.scheduleNext(vm); return; }; @@ -929,7 +931,7 @@ pub const CronJob = struct { .fulfilled => {}, .rejected => { promise.setHandled(this.global.vm()); - vm.runErrorHandler(promise.result(this.global.vm()), null); + vm.unhandledRejection(vm.global, promise.result(this.global.vm()), result); }, } } @@ -954,7 +956,7 @@ pub const CronJob = struct { defer this.deref(); const vm = this.global.bunVM(); const err = if (args.len > 0) args[0] else .js_undefined; - vm.runErrorHandler(err, null); + vm.unhandledRejection(vm.global, err, .js_undefined); this.scheduleNext(vm); return .js_undefined; } diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index ce0f0b22cda3..9038995db837 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -210,31 +210,69 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { } }, 70_000); - test("error in callback is reported but cron continues", async () => { - // Spawn a subprocess so we can observe the uncaught exception on stderr - // and verify the process doesn't crash. + test("sync throw in callback emits uncaughtException", async () => { + // Matches setTimeout: sync throw → uncaughtException. Process exits 1 without a handler. await using proc = Bun.spawn({ cmd: [ bunExe(), "-e", ` - let fires = 0; - const job = Bun.cron("err-test", "* * * * *", () => { - fires++; - if (fires === 1) { - // Stop after second scheduling — the error doesn't kill us - setTimeout(() => { job.stop(); console.log("fires=" + fires); }, 100); - throw new Error("boom"); - } + let caught; + process.on("uncaughtException", e => { caught = e.message; }); + const job = Bun.cron("err-sync", "* * * * *", () => { + setTimeout(() => { job.stop(); console.log("caught=" + caught); process.exit(0); }, 100); + throw new Error("sync-boom"); }); `, ], env: bunEnv, stderr: "pipe", }); + const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stdout.trim()).toBe("caught=sync-boom"); + expect(exitCode).toBe(0); + }, 70_000); + + test("async throw in callback emits unhandledRejection", async () => { + // Matches setTimeout: rejected promise → unhandledRejection. + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + let caught; + process.on("unhandledRejection", e => { caught = e.message; }); + const job = Bun.cron("err-async", "* * * * *", async () => { + setTimeout(() => { job.stop(); console.log("caught=" + caught); process.exit(0); }, 100); + await Bun.sleep(1); + throw new Error("async-boom"); + }); + `, + ], + env: bunEnv, + stderr: "pipe", + }); + const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stdout.trim()).toBe("caught=async-boom"); + expect(exitCode).toBe(0); + }, 70_000); + + test("unhandled cron error exits process like setTimeout does", async () => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + Bun.cron("x", "* * * * *", () => { throw new Error("boom"); }); + setTimeout(() => console.log("still alive"), 61000); + `, + ], + env: bunEnv, + stderr: "pipe", + }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect(stdout.trim()).toBe("fires=1"); + expect(stdout).toBe(""); expect(stderr).toContain("boom"); - expect(exitCode).toBe(0); + expect(exitCode).toBe(1); }, 70_000); }); From dc3478427ecc148c943d0f7446dda938853688dd Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Mon, 30 Mar 2026 21:21:10 -0700 Subject: [PATCH 05/58] Address review feedback: per-VM job map, validate before replace MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Key jobs_map by (VirtualMachine, name) with mutex — workers registering the same name no longer race on each other's timer heaps - Stop old job only after the new expression is confirmed schedulable — Bun.cron('x', '0 0 30 2 *', cb) no longer kills the existing 'x' job before throwing - Use MaybePromise<void> for handler return type --- packages/bun-types/bun.d.ts | 2 +- src/bun.js/api/cron.zig | 64 +++++++++++++++++------- test/js/bun/cron/in-process-cron.test.ts | 16 ++++++ 3 files changed, 62 insertions(+), 20 deletions(-) diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index 06db95f4b80a..f655d98d0a23 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7493,7 +7493,7 @@ declare module "bun" { * @see {@link CronJob} for the returned handle. * @see {@link Bun.cron.parse} to preview the next fire time. */ - (name: string, schedule: CronWithAutocomplete, handler: () => void | Promise<void>): CronJob; + (name: string, schedule: CronWithAutocomplete, handler: () => MaybePromise<void>): CronJob; /** * Register an **OS-level** cron job that runs a JavaScript/TypeScript module on a schedule. * diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index e893075e9319..b1480cb29197 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -842,7 +842,21 @@ pub const CronJob = struct { pub const new = bun.TrivialNew(@This()); - var jobs_map: std.StringHashMapUnmanaged(*CronJob) = .{}; + const JobKey = struct { + vm: *jsc.VirtualMachine, + name: []const u8, + + const Context = struct { + pub fn hash(_: Context, k: JobKey) u64 { + return bun.hash(k.name) ^ @intFromPtr(k.vm); + } + pub fn eql(_: Context, a: JobKey, b: JobKey) bool { + return a.vm == b.vm and bun.strings.eql(a.name, b.name); + } + }; + }; + var jobs_map: std.HashMapUnmanaged(JobKey, *CronJob, JobKey.Context, std.hash_map.default_max_load_percentage) = .{}; + var jobs_lock: bun.Mutex = .{}; fn ref(this: *CronJob) void { this.#ref_count += 1; @@ -965,10 +979,13 @@ pub const CronJob = struct { if (this.stopped) return callframe.this(); this.stopped = true; - if (jobs_map.fetchRemove(this.name)) |kv| - bun.default_allocator.free(kv.key); - const vm = this.global.bunVM(); + { + jobs_lock.lock(); + defer jobs_lock.unlock(); + if (jobs_map.fetchRemove(.{ .vm = vm, .name = this.name })) |kv| + bun.default_allocator.free(kv.key.name); + } if (this.event_loop_timer.state == .ACTIVE) vm.timer.remove(&this.event_loop_timer); this.cleanupAfterStop(vm); @@ -1022,18 +1039,7 @@ pub const CronJob = struct { const parsed = CronExpression.parse(schedule_slice.slice()) catch return globalObject.throwInvalidArguments("Invalid cron expression. Expected 5 space-separated fields (minute hour day month weekday), each being *, a number, or a range/step pattern", .{}); - // Stop any existing job with this name (makes --hot re-registration work). - if (jobs_map.fetchRemove(name_slice.slice())) |existing| { - bun.default_allocator.free(existing.key); - const old = existing.value; - if (!old.stopped) { - old.stopped = true; - const vm = globalObject.bunVM(); - if (old.event_loop_timer.state == .ACTIVE) - vm.timer.remove(&old.event_loop_timer); - old.cleanupAfterStop(vm); - } - } + const vm = globalObject.bunVM(); const job = CronJob.new(.{ .global = globalObject, @@ -1051,15 +1057,35 @@ pub const CronJob = struct { return globalObject.throwInvalidArguments("Cron expression '{s}' has no future occurrences", .{schedule_slice.slice()}); }; + // New job is valid — now safe to stop any existing job with this + // (vm, name) key (makes --hot re-registration work). + { + jobs_lock.lock(); + defer jobs_lock.unlock(); + if (jobs_map.fetchRemove(.{ .vm = vm, .name = name_slice.slice() })) |existing| { + bun.default_allocator.free(existing.key.name); + const old = existing.value; + if (!old.stopped) { + old.stopped = true; + if (old.event_loop_timer.state == .ACTIVE) + vm.timer.remove(&old.event_loop_timer); + old.cleanupAfterStop(vm); + } + } + } + const js_value = job.toJS(globalObject); job.this_value.setStrong(js_value, globalObject); - const vm = globalObject.bunVM(); job.poll.ref(vm); vm.timer.update(&job.event_loop_timer, &next_time); - const key = bun.handleOom(bun.default_allocator.dupe(u8, name_slice.slice())); - bun.handleOom(jobs_map.put(bun.default_allocator, key, job)); + { + jobs_lock.lock(); + defer jobs_lock.unlock(); + const key_name = bun.handleOom(bun.default_allocator.dupe(u8, name_slice.slice())); + bun.handleOom(jobs_map.put(bun.default_allocator, .{ .vm = vm, .name = key_name }, job)); + } return js_value; } diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index 9038995db837..ad9c625b025d 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -19,6 +19,22 @@ describe("Bun.cron (in-process)", () => { expect(() => Bun.cron("x", "0 0 30 2 *", () => {})).toThrow(/no future occurrences/); }); + test("invalid replacement expression does not kill existing job", () => { + const job1 = Bun.cron("keep-me", "* * * * *", () => {}); + try { + // Feb 30 has no future occurrence — should throw WITHOUT stopping job1 + expect(() => Bun.cron("keep-me", "0 0 30 2 *", () => {})).toThrow(/no future occurrences/); + // job1 should still be registered and active + expect(job1.name).toBe("keep-me"); + // Registering a valid replacement should still work after the failed attempt + const job2 = Bun.cron("keep-me", "@daily", () => {}); + expect(job2.cron).toBe("@daily"); + job2.stop(); + } finally { + job1.stop(); + } + }); + test("returns CronJob with name and cron getters", () => { const job = Bun.cron("test-getters", "* * * * *", () => {}); try { From 1d8acc85900df553c53d16c0e4424604974b37d0 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Mon, 30 Mar 2026 21:24:42 -0700 Subject: [PATCH 06/58] Fix JSDoc example: use absolute URL in fetch --- packages/bun-types/bun.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index f655d98d0a23..dea8b30ef22a 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7482,7 +7482,7 @@ declare module "bun" { * }); * * // Background healthcheck that doesn't block process exit - * Bun.cron("ping", "*\/30 * * * *", () => fetch("/health")).unref(); + * Bun.cron("ping", "*\/30 * * * *", () => fetch("https://example.com/health")).unref(); * * // Stop conditionally * const job = Bun.cron("poll", "* * * * *", async () => { From e7422f0d97c5fdad914f3dffa6e1e25a34aa4be7 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Mon, 30 Mar 2026 21:40:45 -0700 Subject: [PATCH 07/58] Add CronJob._fire() to make firing tests instant Reschedules the timer to 1ms from now so the real EventLoopTimer dispatch path fires it on the next tick. Tests go from ~43s (waiting for real minute boundaries) to ~1.3s. --- src/bun.js/api/cron.classes.ts | 4 ++ src/bun.js/api/cron.zig | 10 +++ test/js/bun/cron/in-process-cron.test.ts | 86 ++++++++++++++---------- 3 files changed, 65 insertions(+), 35 deletions(-) diff --git a/src/bun.js/api/cron.classes.ts b/src/bun.js/api/cron.classes.ts index 4aceff29a8a3..a58eed784955 100644 --- a/src/bun.js/api/cron.classes.ts +++ b/src/bun.js/api/cron.classes.ts @@ -22,6 +22,10 @@ export default [ fn: "doUnref", length: 0, }, + _fire: { + fn: "doFire", + length: 0, + }, name: { getter: "getName", cache: true, diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index b1480cb29197..f01e17b3d2ff 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -1009,6 +1009,16 @@ pub const CronJob = struct { return callframe.this(); } + /// Reschedule to fire on the next event loop tick instead of waiting + /// for the cron expression. For tests only — does not respect no-overlap. + pub fn doFire(this: *CronJob, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + if (this.stopped) return callframe.this(); + const vm = this.global.bunVM(); + const soon = bun.timespec.msFromNow(.allow_mocked_time, 1); + vm.timer.update(&this.event_loop_timer, &soon); + return callframe.this(); + } + pub fn getName(this: *CronJob, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, this.name); } diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index ad9c625b025d..6f50b83ecba3 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -172,62 +172,51 @@ describe("Bun.cron (in-process)", () => { }); }); -describe.concurrent("Bun.cron (in-process) — firing", () => { - // This test waits for a real cron fire, which takes up to 60 seconds. - // The cron expression "* * * * *" fires at the top of every minute. - test("callback fires at minute boundary", async () => { +// These use ._fire() to trigger immediately instead of waiting for the minute boundary. +describe("Bun.cron (in-process) — firing", () => { + test("callback fires via _fire()", async () => { let fired = 0; - let resolve: () => void; - const promise = new Promise<void>(r => { - resolve = r; - }); + const { promise, resolve } = Promise.withResolvers<void>(); const job = Bun.cron("fire-test", "* * * * *", () => { fired++; - resolve!(); + resolve(); }); try { + // @ts-expect-error test-only + job._fire(); await promise; expect(fired).toBe(1); } finally { job.stop(); } - }, 70_000); + }); - test("async callback delays next scheduling", async () => { - // The callback returns a Promise; next fire is scheduled only after it resolves. - // We can't easily observe the timing without waiting 2+ minutes, so we just - // verify no crash and that stop() during the pending promise works. - let resolveHandler: () => void; - const handlerPromise = new Promise<void>(r => { - resolveHandler = r; - }); - let fireResolve: () => void; - const firePromise = new Promise<void>(r => { - fireResolve = r; - }); + test("stop() during pending async callback prevents reschedule", async () => { + const { promise: handlerPromise, resolve: resolveHandler } = Promise.withResolvers<void>(); + const { promise: firePromise, resolve: fireResolve } = Promise.withResolvers<void>(); const job = Bun.cron("async-test", "* * * * *", async () => { - fireResolve!(); + fireResolve(); await handlerPromise; }); try { + // @ts-expect-error test-only + job._fire(); await firePromise; - // Handler is now awaiting; stop while it's pending + // Handler is awaiting; stop while pending job.stop(); - // Let the handler complete - resolveHandler!(); + resolveHandler(); await Bun.sleep(10); - // No crash, no second fire + // No crash, no reschedule (stopped before promise settled) } finally { job.stop(); } - }, 70_000); + }); test("sync throw in callback emits uncaughtException", async () => { - // Matches setTimeout: sync throw → uncaughtException. Process exits 1 without a handler. await using proc = Bun.spawn({ cmd: [ bunExe(), @@ -239,6 +228,7 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { setTimeout(() => { job.stop(); console.log("caught=" + caught); process.exit(0); }, 100); throw new Error("sync-boom"); }); + job._fire(); `, ], env: bunEnv, @@ -247,10 +237,9 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); expect(stdout.trim()).toBe("caught=sync-boom"); expect(exitCode).toBe(0); - }, 70_000); + }); test("async throw in callback emits unhandledRejection", async () => { - // Matches setTimeout: rejected promise → unhandledRejection. await using proc = Bun.spawn({ cmd: [ bunExe(), @@ -263,6 +252,7 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { await Bun.sleep(1); throw new Error("async-boom"); }); + job._fire(); `, ], env: bunEnv, @@ -271,7 +261,7 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); expect(stdout.trim()).toBe("caught=async-boom"); expect(exitCode).toBe(0); - }, 70_000); + }); test("unhandled cron error exits process like setTimeout does", async () => { await using proc = Bun.spawn({ @@ -279,8 +269,9 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { bunExe(), "-e", ` - Bun.cron("x", "* * * * *", () => { throw new Error("boom"); }); - setTimeout(() => console.log("still alive"), 61000); + const job = Bun.cron("x", "* * * * *", () => { throw new Error("boom"); }); + setTimeout(() => console.log("still alive"), 1000); + job._fire(); `, ], env: bunEnv, @@ -290,5 +281,30 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { expect(stdout).toBe(""); expect(stderr).toContain("boom"); expect(exitCode).toBe(1); - }, 70_000); + }); + + test("fires repeatedly and reschedules after each callback", async () => { + let fires = 0; + const job = Bun.cron("repeat-test", "* * * * *", () => { + fires++; + }); + try { + for (let i = 0; i < 3; i++) { + const { promise, resolve } = Promise.withResolvers<void>(); + const prev = fires; + const check = setInterval(() => { + if (fires > prev) { + clearInterval(check); + resolve(); + } + }, 5); + // @ts-expect-error test-only + job._fire(); + await promise; + } + expect(fires).toBe(3); + } finally { + job.stop(); + } + }); }); From da3d51fb07dd825d38df52ea014386976368a0e2 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Mon, 30 Mar 2026 21:43:27 -0700 Subject: [PATCH 08/58] Revert "Add CronJob._fire() to make firing tests instant" This reverts commit bc22cfbe3cc15e30c6379ced362760d3c389b14c. --- src/bun.js/api/cron.classes.ts | 4 -- src/bun.js/api/cron.zig | 10 --- test/js/bun/cron/in-process-cron.test.ts | 86 ++++++++++-------------- 3 files changed, 35 insertions(+), 65 deletions(-) diff --git a/src/bun.js/api/cron.classes.ts b/src/bun.js/api/cron.classes.ts index a58eed784955..4aceff29a8a3 100644 --- a/src/bun.js/api/cron.classes.ts +++ b/src/bun.js/api/cron.classes.ts @@ -22,10 +22,6 @@ export default [ fn: "doUnref", length: 0, }, - _fire: { - fn: "doFire", - length: 0, - }, name: { getter: "getName", cache: true, diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index f01e17b3d2ff..b1480cb29197 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -1009,16 +1009,6 @@ pub const CronJob = struct { return callframe.this(); } - /// Reschedule to fire on the next event loop tick instead of waiting - /// for the cron expression. For tests only — does not respect no-overlap. - pub fn doFire(this: *CronJob, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { - if (this.stopped) return callframe.this(); - const vm = this.global.bunVM(); - const soon = bun.timespec.msFromNow(.allow_mocked_time, 1); - vm.timer.update(&this.event_loop_timer, &soon); - return callframe.this(); - } - pub fn getName(this: *CronJob, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, this.name); } diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index 6f50b83ecba3..ad9c625b025d 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -172,51 +172,62 @@ describe("Bun.cron (in-process)", () => { }); }); -// These use ._fire() to trigger immediately instead of waiting for the minute boundary. -describe("Bun.cron (in-process) — firing", () => { - test("callback fires via _fire()", async () => { +describe.concurrent("Bun.cron (in-process) — firing", () => { + // This test waits for a real cron fire, which takes up to 60 seconds. + // The cron expression "* * * * *" fires at the top of every minute. + test("callback fires at minute boundary", async () => { let fired = 0; - const { promise, resolve } = Promise.withResolvers<void>(); + let resolve: () => void; + const promise = new Promise<void>(r => { + resolve = r; + }); const job = Bun.cron("fire-test", "* * * * *", () => { fired++; - resolve(); + resolve!(); }); try { - // @ts-expect-error test-only - job._fire(); await promise; expect(fired).toBe(1); } finally { job.stop(); } - }); + }, 70_000); - test("stop() during pending async callback prevents reschedule", async () => { - const { promise: handlerPromise, resolve: resolveHandler } = Promise.withResolvers<void>(); - const { promise: firePromise, resolve: fireResolve } = Promise.withResolvers<void>(); + test("async callback delays next scheduling", async () => { + // The callback returns a Promise; next fire is scheduled only after it resolves. + // We can't easily observe the timing without waiting 2+ minutes, so we just + // verify no crash and that stop() during the pending promise works. + let resolveHandler: () => void; + const handlerPromise = new Promise<void>(r => { + resolveHandler = r; + }); + let fireResolve: () => void; + const firePromise = new Promise<void>(r => { + fireResolve = r; + }); const job = Bun.cron("async-test", "* * * * *", async () => { - fireResolve(); + fireResolve!(); await handlerPromise; }); try { - // @ts-expect-error test-only - job._fire(); await firePromise; - // Handler is awaiting; stop while pending + // Handler is now awaiting; stop while it's pending job.stop(); - resolveHandler(); + // Let the handler complete + resolveHandler!(); await Bun.sleep(10); - // No crash, no reschedule (stopped before promise settled) + // No crash, no second fire } finally { job.stop(); } - }); + }, 70_000); test("sync throw in callback emits uncaughtException", async () => { + // Matches setTimeout: sync throw → uncaughtException. Process exits 1 without a handler. await using proc = Bun.spawn({ cmd: [ bunExe(), @@ -228,7 +239,6 @@ describe("Bun.cron (in-process) — firing", () => { setTimeout(() => { job.stop(); console.log("caught=" + caught); process.exit(0); }, 100); throw new Error("sync-boom"); }); - job._fire(); `, ], env: bunEnv, @@ -237,9 +247,10 @@ describe("Bun.cron (in-process) — firing", () => { const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); expect(stdout.trim()).toBe("caught=sync-boom"); expect(exitCode).toBe(0); - }); + }, 70_000); test("async throw in callback emits unhandledRejection", async () => { + // Matches setTimeout: rejected promise → unhandledRejection. await using proc = Bun.spawn({ cmd: [ bunExe(), @@ -252,7 +263,6 @@ describe("Bun.cron (in-process) — firing", () => { await Bun.sleep(1); throw new Error("async-boom"); }); - job._fire(); `, ], env: bunEnv, @@ -261,7 +271,7 @@ describe("Bun.cron (in-process) — firing", () => { const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); expect(stdout.trim()).toBe("caught=async-boom"); expect(exitCode).toBe(0); - }); + }, 70_000); test("unhandled cron error exits process like setTimeout does", async () => { await using proc = Bun.spawn({ @@ -269,9 +279,8 @@ describe("Bun.cron (in-process) — firing", () => { bunExe(), "-e", ` - const job = Bun.cron("x", "* * * * *", () => { throw new Error("boom"); }); - setTimeout(() => console.log("still alive"), 1000); - job._fire(); + Bun.cron("x", "* * * * *", () => { throw new Error("boom"); }); + setTimeout(() => console.log("still alive"), 61000); `, ], env: bunEnv, @@ -281,30 +290,5 @@ describe("Bun.cron (in-process) — firing", () => { expect(stdout).toBe(""); expect(stderr).toContain("boom"); expect(exitCode).toBe(1); - }); - - test("fires repeatedly and reschedules after each callback", async () => { - let fires = 0; - const job = Bun.cron("repeat-test", "* * * * *", () => { - fires++; - }); - try { - for (let i = 0; i < 3; i++) { - const { promise, resolve } = Promise.withResolvers<void>(); - const prev = fires; - const check = setInterval(() => { - if (fires > prev) { - clearInterval(check); - resolve(); - } - }, 5); - // @ts-expect-error test-only - job._fire(); - await promise; - } - expect(fires).toBe(3); - } finally { - job.stop(); - } - }); + }, 70_000); }); From a877424e9232dfc7f3acdf2d2b3a1c92a7ef6f2a Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 13:31:34 -0700 Subject: [PATCH 09/58] make it disposable also always clear on --hot and remove the requirement for a name --- packages/bun-types/bun.d.ts | 33 ++-- src/bun.js/VirtualMachine.zig | 1 + src/bun.js/api/cron.classes.ts | 8 +- src/bun.js/api/cron.zig | 116 +++++------- test/integration/bun-types/fixture/cron.ts | 11 ++ test/js/bun/cron/in-process-cron.test.ts | 210 ++++++++++----------- 6 files changed, 185 insertions(+), 194 deletions(-) diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index dea8b30ef22a..f1f9d47b70dc 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7386,16 +7386,14 @@ declare module "bun" { * * @example * ```ts - * const job = Bun.cron("cleanup", "0 * * * *", async () => { + * const job = Bun.cron("0 * * * *", async () => { * await cleanupTempFiles(); * }); * // Later: * job.stop(); * ``` */ - interface CronJob { - /** The name this job was registered with. */ - readonly name: string; + interface CronJob extends Disposable { /** The cron expression string. */ readonly cron: string; /** Cancel this cron job. The callback will not fire again. */ @@ -7435,7 +7433,7 @@ declare module "bun" { * * ```ts * process.on("unhandledRejection", (err) => log.error(err)); // keep going - * Bun.cron("flaky", "* * * * *", async () => { await mightThrow(); }); + * Bun.cron("* * * * *", async () => { await mightThrow(); }); * ``` * * ### Cron expression syntax @@ -7459,33 +7457,34 @@ declare module "bun" { * * ### Lifecycle & `--hot` * - * Calling `Bun.cron()` again with the same `name` stops the previous job and replaces it, - * so top-level `Bun.cron()` calls are safe under `bun --hot` — reloading your module won't - * leak timers. By default the job keeps the process alive (like `setInterval`); call - * `.unref()` to let the process exit naturally when nothing else is pending. + * Under `bun --hot`, all in-process cron jobs are stopped immediately before the module + * graph is re-evaluated. Each `Bun.cron()` call still in your source then re-registers, + * so editing the schedule, editing the callback, or **deleting the line entirely** all + * take effect on save without leaking timers. + * + * By default the job keeps the process alive (like `setInterval`); call `.unref()` to let + * the process exit naturally when nothing else is pending. * - * @param name Unique identifier for this job. Registering the same name again replaces - * the previous job. Not written to the OS — purely for in-process bookkeeping. * @param schedule Cron expression or nickname (e.g. `"*\/5 * * * *"`, `"@hourly"`). * @param handler Function to call on each fire. May return a Promise — the next fire * is not scheduled until it settles. * @returns A {@link CronJob} handle. Chainable: `.stop()`, `.ref()`, `.unref()` all * return the job itself. - * @throws Synchronously if `schedule` is invalid, `name` is empty or not a string, or the - * expression has no future occurrences (e.g. `"0 0 30 2 *"` — February 30th). + * @throws Synchronously if `schedule` is invalid, or the expression has no future + * occurrences (e.g. `"0 0 30 2 *"` — February 30th). * * @example * ```ts * // Hourly cleanup, keeps process alive - * Bun.cron("cleanup", "0 * * * *", async () => { + * Bun.cron("0 * * * *", async () => { * await cleanupTempFiles(); * }); * * // Background healthcheck that doesn't block process exit - * Bun.cron("ping", "*\/30 * * * *", () => fetch("https://example.com/health")).unref(); + * Bun.cron("*\/30 * * * *", () => fetch("https://example.com/health")).unref(); * * // Stop conditionally - * const job = Bun.cron("poll", "* * * * *", async () => { + * const job = Bun.cron("* * * * *", async () => { * if (await isDone()) job.stop(); * }); * ``` @@ -7493,7 +7492,7 @@ declare module "bun" { * @see {@link CronJob} for the returned handle. * @see {@link Bun.cron.parse} to preview the next fire time. */ - (name: string, schedule: CronWithAutocomplete, handler: () => MaybePromise<void>): CronJob; + (schedule: CronWithAutocomplete, handler: () => MaybePromise<void>): CronJob; /** * Register an **OS-level** cron job that runs a JavaScript/TypeScript module on a schedule. * diff --git a/src/bun.js/VirtualMachine.zig b/src/bun.js/VirtualMachine.zig index 2475cf4c275c..5fd0661bb53a 100644 --- a/src/bun.js/VirtualMachine.zig +++ b/src/bun.js/VirtualMachine.zig @@ -746,6 +746,7 @@ pub fn reload(this: *VirtualMachine, _: *HotReloader.Task) void { Output.enableBuffering(); } + jsc.API.cron.CronJob.clearAllForVM(this); this.global.reload() catch @panic("Failed to reload"); this.hot_reload_counter += 1; this.pending_internal_promise = this.reloadEntryPoint(this.main) catch @panic("Failed to reload"); diff --git a/src/bun.js/api/cron.classes.ts b/src/bun.js/api/cron.classes.ts index 4aceff29a8a3..ec34c8153c6b 100644 --- a/src/bun.js/api/cron.classes.ts +++ b/src/bun.js/api/cron.classes.ts @@ -14,6 +14,10 @@ export default [ fn: "stop", length: 0, }, + "@@dispose": { + fn: "stop", + length: 0, + }, ref: { fn: "doRef", length: 0, @@ -22,10 +26,6 @@ export default [ fn: "doUnref", length: 0, }, - name: { - getter: "getName", - cache: true, - }, cron: { getter: "getCron", cache: true, diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index b1480cb29197..eae7f744b9bb 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -413,9 +413,9 @@ pub const CronRegisterJob = struct { pub fn cronRegister(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args = callframe.argumentsAsArray(3); - // In-process callback cron: Bun.cron(name, schedule, handler) - if (args[2].isCallable()) - return CronJob.register(globalObject, args[0], args[1], args[2]); + // In-process callback cron: Bun.cron(schedule, handler) + if (args[1].isCallable()) + return CronJob.register(globalObject, args[0], args[1]); if (!args[0].isString()) return globalObject.throwInvalidArguments("Bun.cron() expects a string path as the first argument", .{}); if (!args[1].isString()) return globalObject.throwInvalidArguments("Bun.cron() expects a string schedule as the second argument", .{}); @@ -812,15 +812,15 @@ pub const CronRemoveJob = struct { // CronJob — in-process callback-style cron (issue #7004) // ============================================================================ // -// Bun.cron(name, "*/5 * * * *", async () => { ... }) +// Bun.cron("*/5 * * * *", async () => { ... }) // // Unlike the OS-level cron above, this runs the callback in the current // process on the event loop. The next execution is scheduled only after the // callback (including any returned Promise) completes, so callbacks never // overlap. Error semantics match setTimeout: sync throws become -// uncaughtException, rejected Promises become unhandledRejection. Calling -// Bun.cron() again with the same name replaces the old job, which makes -// --hot reload work without leaking timers. +// uncaughtException, rejected Promises become unhandledRejection. Under --hot, +// VirtualMachine.reload() calls clearAllForVM before re-evaluating the module +// graph, so deleted Bun.cron() calls don't leave ghost timers. pub const CronJob = struct { pub const js = jsc.Codegen.JSCronJob; @@ -832,7 +832,6 @@ pub const CronJob = struct { callback: jsc.Strong.Optional = .empty, global: *jsc.JSGlobalObject, parsed: CronExpression, - name: []const u8, expression: []const u8, poll: bun.Async.KeepAlive = .{}, this_value: jsc.JSRef = jsc.JSRef.empty(), @@ -842,21 +841,46 @@ pub const CronJob = struct { pub const new = bun.TrivialNew(@This()); - const JobKey = struct { - vm: *jsc.VirtualMachine, - name: []const u8, + // All live in-process cron jobs across all VMs. Named-replacement and + // hot-reload clearing both linear-scan this; an app has at most a handful + // of cron jobs so a hash map is overkill. + var jobs_list: std.ArrayListUnmanaged(*CronJob) = .{}; + var jobs_lock: bun.Mutex = .{}; - const Context = struct { - pub fn hash(_: Context, k: JobKey) u64 { - return bun.hash(k.name) ^ @intFromPtr(k.vm); + fn removeFromListLocked(this: *CronJob) void { + for (jobs_list.items, 0..) |job, i| { + if (job == this) { + _ = jobs_list.swapRemove(i); + return; } - pub fn eql(_: Context, a: JobKey, b: JobKey) bool { - return a.vm == b.vm and bun.strings.eql(a.name, b.name); + } + } + + fn stopInternal(this: *CronJob, vm: *jsc.VirtualMachine) void { + if (this.stopped) return; + this.stopped = true; + if (this.event_loop_timer.state == .ACTIVE) + vm.timer.remove(&this.event_loop_timer); + this.cleanupAfterStop(vm); + } + + /// Called from VirtualMachine.reload() before --hot re-evaluates the + /// module graph. Every Bun.cron() call still in the source will + /// re-register; deleted ones won't, so no ghost jobs survive an edit. + pub fn clearAllForVM(vm: *jsc.VirtualMachine) void { + jobs_lock.lock(); + defer jobs_lock.unlock(); + var i: usize = 0; + while (i < jobs_list.items.len) { + const job = jobs_list.items[i]; + if (job.global.bunVM() == vm) { + job.stopInternal(vm); + _ = jobs_list.swapRemove(i); + } else { + i += 1; } - }; - }; - var jobs_map: std.HashMapUnmanaged(JobKey, *CronJob, JobKey.Context, std.hash_map.default_max_load_percentage) = .{}; - var jobs_lock: bun.Mutex = .{}; + } + } fn ref(this: *CronJob) void { this.#ref_count += 1; @@ -873,7 +897,6 @@ pub const CronJob = struct { fn deinit(this: *CronJob) void { this.callback.deinit(); this.this_value.deinit(); - bun.default_allocator.free(this.name); bun.default_allocator.free(this.expression); } @@ -977,19 +1000,12 @@ pub const CronJob = struct { pub fn stop(this: *CronJob, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { if (this.stopped) return callframe.this(); - this.stopped = true; - - const vm = this.global.bunVM(); { jobs_lock.lock(); defer jobs_lock.unlock(); - if (jobs_map.fetchRemove(.{ .vm = vm, .name = this.name })) |kv| - bun.default_allocator.free(kv.key.name); + this.removeFromListLocked(); } - if (this.event_loop_timer.state == .ACTIVE) - vm.timer.remove(&this.event_loop_timer); - this.cleanupAfterStop(vm); - + this.stopInternal(this.global.bunVM()); return callframe.this(); } @@ -1009,27 +1025,13 @@ pub const CronJob = struct { return callframe.this(); } - pub fn getName(this: *CronJob, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { - return bun.String.createUTF8ForJS(globalObject, this.name); - } - pub fn getCron(this: *CronJob, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, this.expression); } - pub fn register(globalObject: *jsc.JSGlobalObject, name_arg: jsc.JSValue, schedule_arg: jsc.JSValue, callback_arg: jsc.JSValue) bun.JSError!jsc.JSValue { - if (!name_arg.isString()) - return globalObject.throwInvalidArguments("Bun.cron() expects a string name as the first argument", .{}); + pub fn register(globalObject: *jsc.JSGlobalObject, schedule_arg: jsc.JSValue, callback_arg: jsc.JSValue) bun.JSError!jsc.JSValue { if (!schedule_arg.isString()) - return globalObject.throwInvalidArguments("Bun.cron() expects a string cron expression as the second argument", .{}); - - const name_str = try name_arg.toBunString(globalObject); - defer name_str.deref(); - const name_slice = name_str.toUTF8(bun.default_allocator); - defer name_slice.deinit(); - - if (name_slice.slice().len == 0) - return globalObject.throwInvalidArguments("Bun.cron() name must not be empty", .{}); + return globalObject.throwInvalidArguments("Bun.cron() expects a string cron expression", .{}); const schedule_str = try schedule_arg.toBunString(globalObject); defer schedule_str.deref(); @@ -1044,34 +1046,21 @@ pub const CronJob = struct { const job = CronJob.new(.{ .global = globalObject, .parsed = parsed, - .name = bun.handleOom(bun.default_allocator.dupe(u8, name_slice.slice())), .expression = bun.handleOom(bun.default_allocator.dupe(u8, schedule_slice.slice())), }); job.callback = .create(callback_arg, globalObject); const next_time = job.computeNextTimespec() orelse { job.callback.deinit(); - bun.default_allocator.free(job.name); bun.default_allocator.free(job.expression); bun.destroy(job); return globalObject.throwInvalidArguments("Cron expression '{s}' has no future occurrences", .{schedule_slice.slice()}); }; - // New job is valid — now safe to stop any existing job with this - // (vm, name) key (makes --hot re-registration work). { jobs_lock.lock(); defer jobs_lock.unlock(); - if (jobs_map.fetchRemove(.{ .vm = vm, .name = name_slice.slice() })) |existing| { - bun.default_allocator.free(existing.key.name); - const old = existing.value; - if (!old.stopped) { - old.stopped = true; - if (old.event_loop_timer.state == .ACTIVE) - vm.timer.remove(&old.event_loop_timer); - old.cleanupAfterStop(vm); - } - } + bun.handleOom(jobs_list.append(bun.default_allocator, job)); } const js_value = job.toJS(globalObject); @@ -1080,13 +1069,6 @@ pub const CronJob = struct { job.poll.ref(vm); vm.timer.update(&job.event_loop_timer, &next_time); - { - jobs_lock.lock(); - defer jobs_lock.unlock(); - const key_name = bun.handleOom(bun.default_allocator.dupe(u8, name_slice.slice())); - bun.handleOom(jobs_map.put(bun.default_allocator, .{ .vm = vm, .name = key_name }, job)); - } - return js_value; } }; diff --git a/test/integration/bun-types/fixture/cron.ts b/test/integration/bun-types/fixture/cron.ts index 4864b2d4b031..2cfbb68da54e 100644 --- a/test/integration/bun-types/fixture/cron.ts +++ b/test/integration/bun-types/fixture/cron.ts @@ -40,6 +40,17 @@ expectType(Bun.cron.remove("weekly-report")).is<Promise<void>>(); expectType(Bun.cron("./worker.ts", "@daily", "daily")).is<Promise<void>>(); +// -- In-process callback overload -- + +expectType(Bun.cron("* * * * *", () => {})).is<Bun.CronJob>(); +expectType(Bun.cron("@hourly", async () => {})).is<Bun.CronJob>(); +using job = Bun.cron("0 * * * *", () => {}); +expectType(job.cron).is<string>(); +expectType(job.stop()).is<Bun.CronJob>(); +expectType(job.ref()).is<Bun.CronJob>(); +expectType(job.unref()).is<Bun.CronJob>(); +expectType(job[Symbol.dispose]()).is<void>(); + // -- @ts-expect-error cases -- // @ts-expect-error - missing schedule and title diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index ad9c625b025d..85bea9899f72 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -1,53 +1,43 @@ import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe, normalizeBunSnapshot } from "harness"; +import { bunEnv, bunExe, normalizeBunSnapshot, tempDir } from "harness"; +import { join } from "node:path"; describe("Bun.cron (in-process)", () => { test("validates cron expression", () => { - expect(() => Bun.cron("x", "invalid expr", () => {})).toThrow(/Invalid cron expression/); - expect(() => Bun.cron("x", "* * * *", () => {})).toThrow(/Invalid cron expression/); - expect(() => Bun.cron("x", "60 * * * *", () => {})).toThrow(/Invalid cron expression/); + expect(() => Bun.cron("invalid expr", () => {})).toThrow(/Invalid cron expression/); + expect(() => Bun.cron("* * * *", () => {})).toThrow(/Invalid cron expression/); + expect(() => Bun.cron("60 * * * *", () => {})).toThrow(/Invalid cron expression/); }); - test("validates name is non-empty string", () => { - expect(() => Bun.cron("", "* * * * *", () => {})).toThrow(/name must not be empty/); + test("validates schedule is a string", () => { // @ts-expect-error - expect(() => Bun.cron(123, "* * * * *", () => {})).toThrow(/string name/); + expect(() => Bun.cron(123, () => {})).toThrow(/string cron expression/); }); test("rejects expressions with no future occurrences", () => { // Feb 30 never exists - expect(() => Bun.cron("x", "0 0 30 2 *", () => {})).toThrow(/no future occurrences/); + expect(() => Bun.cron("0 0 30 2 *", () => {})).toThrow(/no future occurrences/); }); - test("invalid replacement expression does not kill existing job", () => { - const job1 = Bun.cron("keep-me", "* * * * *", () => {}); - try { - // Feb 30 has no future occurrence — should throw WITHOUT stopping job1 - expect(() => Bun.cron("keep-me", "0 0 30 2 *", () => {})).toThrow(/no future occurrences/); - // job1 should still be registered and active - expect(job1.name).toBe("keep-me"); - // Registering a valid replacement should still work after the failed attempt - const job2 = Bun.cron("keep-me", "@daily", () => {}); - expect(job2.cron).toBe("@daily"); - job2.stop(); - } finally { - job1.stop(); - } + test("returns CronJob with cron getter", () => { + using job = Bun.cron("* * * * *", () => {}); + expect(job.cron).toBe("* * * * *"); }); - test("returns CronJob with name and cron getters", () => { - const job = Bun.cron("test-getters", "* * * * *", () => {}); - try { - expect(job.name).toBe("test-getters"); - expect(job.cron).toBe("* * * * *"); - } finally { - job.stop(); + test("is Disposable", () => { + let j!: Bun.CronJob; + { + using job = Bun.cron("* * * * *", () => {}); + j = job; + expect(job[Symbol.dispose]).toBe(job.stop); } + // Disposed at scope exit; stop() is idempotent so this is just a smoke check + expect(() => j.stop()).not.toThrow(); }); test("stop() cancels before first fire", () => { let called = false; - const job = Bun.cron("test-stop", "* * * * *", () => { + const job = Bun.cron("* * * * *", () => { called = true; }); job.stop(); @@ -56,7 +46,7 @@ describe("Bun.cron (in-process)", () => { }); test("stop() is idempotent", () => { - const job = Bun.cron("test-stop-idem", "* * * * *", () => {}); + const job = Bun.cron("* * * * *", () => {}); expect(() => { job.stop(); job.stop(); @@ -65,56 +55,29 @@ describe("Bun.cron (in-process)", () => { }); test("ref()/unref() are chainable", () => { - const job = Bun.cron("test-chain", "* * * * *", () => {}); - try { - expect(job.unref()).toBe(job); - expect(job.ref()).toBe(job); - expect(job.stop()).toBe(job); - } finally { - job.stop(); - } + using job = Bun.cron("* * * * *", () => {}); + expect(job.unref()).toBe(job); + expect(job.ref()).toBe(job); + expect(job.stop()).toBe(job); }); - test("same name replaces previous job", () => { - let calls1 = 0; - let calls2 = 0; - const job1 = Bun.cron("replace-test", "* * * * *", () => { - calls1++; - }); - // Registering again with same name should stop job1 - const job2 = Bun.cron("replace-test", "* * * * *", () => { - calls2++; - }); - try { - // Both handles exist but only job2 is active - expect(job1.name).toBe("replace-test"); - expect(job2.name).toBe("replace-test"); - // Stopping job2 is what matters now; job1 was already stopped by replacement - job1.stop(); // no-op, already stopped - job2.stop(); - } finally { - job2.stop(); - } - expect(calls1).toBe(0); - expect(calls2).toBe(0); + test("multiple jobs coexist independently", () => { + using a = Bun.cron("* * * * *", () => {}); + using b = Bun.cron("* * * * *", () => {}); + expect(a).not.toBe(b); + a.stop(); + // b is still a valid handle after stopping a + expect(typeof b.stop).toBe("function"); }); test("accepts @nicknames", () => { - const job = Bun.cron("test-nickname", "@hourly", () => {}); - try { - expect(job.cron).toBe("@hourly"); - } finally { - job.stop(); - } + using job = Bun.cron("@hourly", () => {}); + expect(job.cron).toBe("@hourly"); }); test("supports named weekdays and months", () => { - const job = Bun.cron("test-names", "0 9 * JAN-DEC MON-FRI", () => {}); - try { - expect(job.cron).toBe("0 9 * JAN-DEC MON-FRI"); - } finally { - job.stop(); - } + using job = Bun.cron("0 9 * JAN-DEC MON-FRI", () => {}); + expect(job.cron).toBe("0 9 * JAN-DEC MON-FRI"); }); test("keeps process alive by default; unref() allows exit", async () => { @@ -125,7 +88,7 @@ describe("Bun.cron (in-process)", () => { bunExe(), "-e", ` - const job = Bun.cron("x", "* * * * *", () => {}); + const job = Bun.cron("* * * * *", () => {}); job.unref(); console.log("scheduled"); `, @@ -145,7 +108,7 @@ describe("Bun.cron (in-process)", () => { bunExe(), "-e", ` - const job = Bun.cron("x", "* * * * *", () => {}); + const job = Bun.cron("* * * * *", () => {}); console.log("scheduled"); setTimeout(() => { job.stop(); console.log("stopped"); }, 50); `, @@ -159,16 +122,12 @@ describe("Bun.cron (in-process)", () => { }); test("distinguishes callback overload from OS-level overload", () => { - // Callable 3rd arg → in-process; string 3rd arg → OS-level. + // Callable 2nd arg → in-process; 3-string-arg → OS-level. // We only verify the callback path here; the string path is covered elsewhere. - const job = Bun.cron("overload-test", "* * * * *", () => {}); - try { - // CronJob has stop(); Promise would not - expect(typeof job.stop).toBe("function"); - expect(job).not.toBeInstanceOf(Promise); - } finally { - job.stop(); - } + using job = Bun.cron("* * * * *", () => {}); + // CronJob has stop(); Promise would not + expect(typeof job.stop).toBe("function"); + expect(job).not.toBeInstanceOf(Promise); }); }); @@ -182,17 +141,13 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { resolve = r; }); - const job = Bun.cron("fire-test", "* * * * *", () => { + using job = Bun.cron("* * * * *", () => { fired++; resolve!(); }); - try { - await promise; - expect(fired).toBe(1); - } finally { - job.stop(); - } + await promise; + expect(fired).toBe(1); }, 70_000); test("async callback delays next scheduling", async () => { @@ -208,22 +163,18 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { fireResolve = r; }); - const job = Bun.cron("async-test", "* * * * *", async () => { + using job = Bun.cron("* * * * *", async () => { fireResolve!(); await handlerPromise; }); - try { - await firePromise; - // Handler is now awaiting; stop while it's pending - job.stop(); - // Let the handler complete - resolveHandler!(); - await Bun.sleep(10); - // No crash, no second fire - } finally { - job.stop(); - } + await firePromise; + // Handler is now awaiting; stop while it's pending + job.stop(); + // Let the handler complete + resolveHandler!(); + await Bun.sleep(10); + // No crash, no second fire }, 70_000); test("sync throw in callback emits uncaughtException", async () => { @@ -235,7 +186,7 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { ` let caught; process.on("uncaughtException", e => { caught = e.message; }); - const job = Bun.cron("err-sync", "* * * * *", () => { + const job = Bun.cron("* * * * *", () => { setTimeout(() => { job.stop(); console.log("caught=" + caught); process.exit(0); }, 100); throw new Error("sync-boom"); }); @@ -258,7 +209,7 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { ` let caught; process.on("unhandledRejection", e => { caught = e.message; }); - const job = Bun.cron("err-async", "* * * * *", async () => { + const job = Bun.cron("* * * * *", async () => { setTimeout(() => { job.stop(); console.log("caught=" + caught); process.exit(0); }, 100); await Bun.sleep(1); throw new Error("async-boom"); @@ -279,7 +230,7 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { bunExe(), "-e", ` - Bun.cron("x", "* * * * *", () => { throw new Error("boom"); }); + Bun.cron("* * * * *", () => { throw new Error("boom"); }); setTimeout(() => console.log("still alive"), 61000); `, ], @@ -291,4 +242,51 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { expect(stderr).toContain("boom"); expect(exitCode).toBe(1); }, 70_000); + + test("--hot reload clears jobs deleted from source", async () => { + // We need enough time before the next minute boundary to spawn, see v1 + // evaluate, edit the file, and let --hot reload v2. If we're within 10s + // of a boundary, wait it out so the edit reliably lands first. + const sec = new Date().getSeconds(); + if (sec >= 50) await Bun.sleep((61 - sec) * 1000); + + using dir = tempDir("cron-hot", { + "app.ts": ` + import { writeFileSync } from "node:fs"; + writeFileSync("v1.evaluated", ""); + Bun.cron("* * * * *", () => writeFileSync("ghost.fired", "")); + `, + }); + const path = (f: string) => join(String(dir), f); + + await using proc = Bun.spawn({ + cmd: [bunExe(), "--hot", "--no-clear-screen", "app.ts"], + env: bunEnv, + cwd: String(dir), + stdout: "ignore", + stderr: "ignore", + }); + + while (!(await Bun.file(path("v1.evaluated")).exists())) await Bun.sleep(10); + + // Delete the ghost cron; replace with a sentinel that fires on the same + // boundary. When the sentinel fires, ghost.fired must NOT exist. + await Bun.write( + path("app.ts"), + ` + import { writeFileSync, existsSync } from "node:fs"; + writeFileSync("v2.evaluated", ""); + Bun.cron("* * * * *", () => { + writeFileSync("result", existsSync("ghost.fired") ? "GHOST_FIRED" : "ok"); + process.exit(0); + }); + `, + ); + + while (!(await Bun.file(path("v2.evaluated")).exists())) await Bun.sleep(10); + await proc.exited; + + expect(await Bun.file(path("result")).text()).toBe("ok"); + expect(await Bun.file(path("ghost.fired")).exists()).toBe(false); + }, 130_000); }); From b885965f3ae14a47f16a7d976271d96738b15f32 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 13:47:03 -0700 Subject: [PATCH 10/58] Address review feedback and simplify CronJob - Remove from jobs_list on natural-expiry/VM-shutdown to prevent dangling pointer after GC (selfStop helper) - Pass actual promise to unhandledRejection in async-reject path - Correct promiseFunctionsSize to 34 - Use bun.ptr.RefCount instead of hand-rolled ref/deref - Drop redundant has_js_ref (KeepAlive self-no-ops) - Consolidate stop() into selfStop, indexOfScalar for list removal - Release pending_promise on stop to avoid pinning old code under --hot --- src/bun.js/api/cron.zig | 98 +++++++++++------------- src/bun.js/bindings/ZigGlobalObject.h | 2 +- test/js/bun/cron/in-process-cron.test.ts | 6 +- 3 files changed, 47 insertions(+), 59 deletions(-) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index eae7f744b9bb..0835480de78b 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -823,37 +823,34 @@ pub const CronRemoveJob = struct { // graph, so deleted Bun.cron() calls don't leave ghost timers. pub const CronJob = struct { + const RefCount = bun.ptr.RefCount(@This(), "ref_count", deinit, .{}); + pub const ref = RefCount.ref; + pub const deref = RefCount.deref; + pub const js = jsc.Codegen.JSCronJob; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; + ref_count: RefCount, event_loop_timer: EventLoopTimer = .{ .tag = .CronJob, .next = .epoch }, callback: jsc.Strong.Optional = .empty, + pending_promise: jsc.Strong.Optional = .empty, global: *jsc.JSGlobalObject, parsed: CronExpression, expression: []const u8, poll: bun.Async.KeepAlive = .{}, this_value: jsc.JSRef = jsc.JSRef.empty(), - #ref_count: u32 = 1, stopped: bool = false, - has_js_ref: bool = true, - - pub const new = bun.TrivialNew(@This()); - // All live in-process cron jobs across all VMs. Named-replacement and - // hot-reload clearing both linear-scan this; an app has at most a handful - // of cron jobs so a hash map is overkill. + // All live in-process cron jobs across all VMs. clearAllForVM linear-scans + // this; an app has at most a handful of cron jobs so a hash map is overkill. var jobs_list: std.ArrayListUnmanaged(*CronJob) = .{}; var jobs_lock: bun.Mutex = .{}; fn removeFromListLocked(this: *CronJob) void { - for (jobs_list.items, 0..) |job, i| { - if (job == this) { - _ = jobs_list.swapRemove(i); - return; - } - } + if (std.mem.indexOfScalar(*CronJob, jobs_list.items, this)) |i| + _ = jobs_list.swapRemove(i); } fn stopInternal(this: *CronJob, vm: *jsc.VirtualMachine) void { @@ -861,9 +858,22 @@ pub const CronJob = struct { this.stopped = true; if (this.event_loop_timer.state == .ACTIVE) vm.timer.remove(&this.event_loop_timer); + this.pending_promise.deinit(); this.cleanupAfterStop(vm); } + /// Self-initiated stop from inside the timer/promise path (natural expiry, + /// callback gone). Removes from jobs_list so GC of the JS wrapper doesn't + /// leave a dangling pointer for clearAllForVM/stop() to read. + fn selfStop(this: *CronJob, vm: *jsc.VirtualMachine) void { + { + jobs_lock.lock(); + defer jobs_lock.unlock(); + this.removeFromListLocked(); + } + this.stopInternal(vm); + } + /// Called from VirtualMachine.reload() before --hot re-evaluates the /// module graph. Every Bun.cron() call still in the source will /// re-register; deleted ones won't, so no ghost jobs survive an edit. @@ -882,22 +892,12 @@ pub const CronJob = struct { } } - fn ref(this: *CronJob) void { - this.#ref_count += 1; - } - - fn deref(this: *CronJob) void { - this.#ref_count -= 1; - if (this.#ref_count == 0) { - this.deinit(); - bun.destroy(this); - } - } - fn deinit(this: *CronJob) void { this.callback.deinit(); + this.pending_promise.deinit(); this.this_value.deinit(); bun.default_allocator.free(this.expression); + bun.destroy(this); } pub fn finalize(this: *CronJob) void { @@ -913,13 +913,9 @@ pub const CronJob = struct { } fn scheduleNext(this: *CronJob, vm: *jsc.VirtualMachine) void { - if (this.stopped) { - this.cleanupAfterStop(vm); - return; - } + if (this.stopped) return; const next_time = this.computeNextTimespec() orelse { - this.stopped = true; - this.cleanupAfterStop(vm); + this.selfStop(vm); return; }; vm.timer.update(&this.event_loop_timer, &next_time); @@ -934,14 +930,14 @@ pub const CronJob = struct { pub fn onTimerFire(this: *CronJob, vm: *jsc.VirtualMachine) void { this.event_loop_timer.state = .FIRED; - if (this.stopped or vm.scriptExecutionStatus() != .running) { - this.cleanupAfterStop(vm); + if (this.stopped) return; + if (vm.scriptExecutionStatus() != .running) { + this.selfStop(vm); return; } const cb = this.callback.get() orelse { - this.stopped = true; - this.cleanupAfterStop(vm); + this.selfStop(vm); return; }; @@ -959,7 +955,9 @@ pub const CronJob = struct { switch (promise.status()) { .pending => { this.ref(); + this.pending_promise.set(this.global, result); result.then(this.global, this, onPromiseResolve, onPromiseReject) catch { + this.pending_promise.deinit(); this.deref(); this.scheduleNext(vm); }; @@ -983,6 +981,7 @@ pub const CronJob = struct { const args = callframe.arguments(); var this: *CronJob = args[args.len - 1].asPromisePtr(CronJob); defer this.deref(); + this.pending_promise.deinit(); this.scheduleNext(this.global.bunVM()); return .js_undefined; } @@ -993,35 +992,25 @@ pub const CronJob = struct { defer this.deref(); const vm = this.global.bunVM(); const err = if (args.len > 0) args[0] else .js_undefined; - vm.unhandledRejection(vm.global, err, .js_undefined); + const promise_value = this.pending_promise.get() orelse .js_undefined; + this.pending_promise.deinit(); + vm.unhandledRejection(vm.global, err, promise_value); this.scheduleNext(vm); return .js_undefined; } pub fn stop(this: *CronJob, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { - if (this.stopped) return callframe.this(); - { - jobs_lock.lock(); - defer jobs_lock.unlock(); - this.removeFromListLocked(); - } - this.stopInternal(this.global.bunVM()); + this.selfStop(this.global.bunVM()); return callframe.this(); } pub fn doRef(this: *CronJob, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { - if (!this.has_js_ref and !this.stopped) { - this.has_js_ref = true; - this.poll.ref(this.global.bunVM()); - } + if (!this.stopped) this.poll.ref(this.global.bunVM()); return callframe.this(); } pub fn doUnref(this: *CronJob, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { - if (this.has_js_ref) { - this.has_js_ref = false; - this.poll.unref(this.global.bunVM()); - } + this.poll.unref(this.global.bunVM()); return callframe.this(); } @@ -1043,7 +1032,8 @@ pub const CronJob = struct { const vm = globalObject.bunVM(); - const job = CronJob.new(.{ + const job = bun.new(CronJob, .{ + .ref_count = .init(), .global = globalObject, .parsed = parsed, .expression = bun.handleOom(bun.default_allocator.dupe(u8, schedule_slice.slice())), @@ -1051,9 +1041,7 @@ pub const CronJob = struct { job.callback = .create(callback_arg, globalObject); const next_time = job.computeNextTimespec() orelse { - job.callback.deinit(); - bun.default_allocator.free(job.expression); - bun.destroy(job); + job.deref(); return globalObject.throwInvalidArguments("Cron expression '{s}' has no future occurrences", .{schedule_slice.slice()}); }; diff --git a/src/bun.js/bindings/ZigGlobalObject.h b/src/bun.js/bindings/ZigGlobalObject.h index e92ab9565b9a..f887f635013a 100644 --- a/src/bun.js/bindings/ZigGlobalObject.h +++ b/src/bun.js/bindings/ZigGlobalObject.h @@ -397,7 +397,7 @@ class GlobalObject : public Bun::GlobalScope { Bun__CronJob__onPromiseResolve, Bun__CronJob__onPromiseReject, }; - static constexpr size_t promiseFunctionsSize = 36; + static constexpr size_t promiseFunctionsSize = 34; static PromiseFunctions promiseHandlerID(SYSV_ABI EncodedJSValue (*handler)(JSC::JSGlobalObject* arg0, JSC::CallFrame* arg1)); diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index 85bea9899f72..9cb440907262 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -29,7 +29,7 @@ describe("Bun.cron (in-process)", () => { { using job = Bun.cron("* * * * *", () => {}); j = job; - expect(job[Symbol.dispose]).toBe(job.stop); + expect(typeof job[Symbol.dispose]).toBe("function"); } // Disposed at scope exit; stop() is idempotent so this is just a smoke check expect(() => j.stop()).not.toThrow(); @@ -208,7 +208,7 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { "-e", ` let caught; - process.on("unhandledRejection", e => { caught = e.message; }); + process.on("unhandledRejection", (e, p) => { caught = e.message + ":" + (p instanceof Promise); }); const job = Bun.cron("* * * * *", async () => { setTimeout(() => { job.stop(); console.log("caught=" + caught); process.exit(0); }, 100); await Bun.sleep(1); @@ -220,7 +220,7 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { stderr: "pipe", }); const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect(stdout.trim()).toBe("caught=async-boom"); + expect(stdout.trim()).toBe("caught=async-boom:true"); expect(exitCode).toBe(0); }, 70_000); From 62f3b9c8355eae2584b229314965b30afc866d17 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 13:50:06 -0700 Subject: [PATCH 11/58] Use Promise.withResolvers in cron firing tests --- test/js/bun/cron/in-process-cron.test.ts | 25 ++++++++---------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index 9cb440907262..07bfe3a7550c 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -136,14 +136,11 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { // The cron expression "* * * * *" fires at the top of every minute. test("callback fires at minute boundary", async () => { let fired = 0; - let resolve: () => void; - const promise = new Promise<void>(r => { - resolve = r; - }); + const { promise, resolve } = Promise.withResolvers<void>(); using job = Bun.cron("* * * * *", () => { fired++; - resolve!(); + resolve(); }); await promise; @@ -154,25 +151,19 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { // The callback returns a Promise; next fire is scheduled only after it resolves. // We can't easily observe the timing without waiting 2+ minutes, so we just // verify no crash and that stop() during the pending promise works. - let resolveHandler: () => void; - const handlerPromise = new Promise<void>(r => { - resolveHandler = r; - }); - let fireResolve: () => void; - const firePromise = new Promise<void>(r => { - fireResolve = r; - }); + const handler = Promise.withResolvers<void>(); + const fire = Promise.withResolvers<void>(); using job = Bun.cron("* * * * *", async () => { - fireResolve!(); - await handlerPromise; + fire.resolve(); + await handler.promise; }); - await firePromise; + await fire.promise; // Handler is now awaiting; stop while it's pending job.stop(); // Let the handler complete - resolveHandler!(); + handler.resolve(); await Bun.sleep(10); // No crash, no second fire }, 70_000); From 5d70794d544e8461cd9e3caa10eba36d32f1b712 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 14:03:16 -0700 Subject: [PATCH 12/58] Clear cron jobs on worker termination; deterministic --hot test - exitAndDeinit calls clearAllForVM so worker cron jobs don't leave stale entries in the process-global jobs_list - --hot test ghost callback gates on v2.evaluated instead of sleeping past the minute boundary --- src/bun.js/api/cron.zig | 5 ++--- src/bun.js/web_worker.zig | 1 + test/js/bun/cron/in-process-cron.test.ts | 14 ++++++-------- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 0835480de78b..9067563c44d2 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -862,9 +862,8 @@ pub const CronJob = struct { this.cleanupAfterStop(vm); } - /// Self-initiated stop from inside the timer/promise path (natural expiry, - /// callback gone). Removes from jobs_list so GC of the JS wrapper doesn't - /// leave a dangling pointer for clearAllForVM/stop() to read. + /// Removes from jobs_list before stopping so GC of the JS wrapper doesn't + /// leave a dangling pointer for clearAllForVM to read. fn selfStop(this: *CronJob, vm: *jsc.VirtualMachine) void { { jobs_lock.lock(); diff --git a/src/bun.js/web_worker.zig b/src/bun.js/web_worker.zig index 781009e788a8..d9d0a33367e3 100644 --- a/src/bun.js/web_worker.zig +++ b/src/bun.js/web_worker.zig @@ -603,6 +603,7 @@ pub fn exitAndDeinit(this: *WebWorker) noreturn { loop = vm.uwsLoop(); this.vm = null; vm.is_shutting_down = true; + jsc.API.cron.CronJob.clearAllForVM(vm); vm.onExit(); exit_code = vm.exit_handler.exit_code; globalObject = vm.global; diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index 07bfe3a7550c..979625814ee3 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -235,17 +235,15 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { }, 70_000); test("--hot reload clears jobs deleted from source", async () => { - // We need enough time before the next minute boundary to spawn, see v1 - // evaluate, edit the file, and let --hot reload v2. If we're within 10s - // of a boundary, wait it out so the edit reliably lands first. - const sec = new Date().getSeconds(); - if (sec >= 50) await Bun.sleep((61 - sec) * 1000); - using dir = tempDir("cron-hot", { "app.ts": ` - import { writeFileSync } from "node:fs"; + import { writeFileSync, existsSync } from "node:fs"; writeFileSync("v1.evaluated", ""); - Bun.cron("* * * * *", () => writeFileSync("ghost.fired", "")); + // A fire before the v2 reload is legitimate (not a ghost) — only + // write the marker if v2 has already evaluated. + Bun.cron("* * * * *", () => { + if (existsSync("v2.evaluated")) writeFileSync("ghost.fired", ""); + }); `, }); const path = (f: string) => join(String(dir), f); From f85aca180bd016c7fef163e5335cba43cc06fe3f Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 15:10:06 -0700 Subject: [PATCH 13/58] Anchor cron to real time; suppress rejection for stopped jobs - computeNextTimespec uses .force_real_time (was mixing real-epoch calendar math with mocked-monotonic deadline under fake timers) - onPromiseReject returns early when stopped so an in-flight rejection after stop()/--hot/worker-exit doesn't emit unhandledRejection with an undefined promise --- src/bun.js/api/cron.zig | 8 +++++++- test/js/bun/cron/in-process-cron.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 9067563c44d2..ae9d1581453b 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -905,10 +905,13 @@ pub const CronJob = struct { } fn computeNextTimespec(this: *CronJob) ?bun.timespec { + // Cron occurrences are calendar-based (real epoch); the timer heap is + // monotonic. Using .allow_mocked_time here would mix the two timebases + // under fake timers — anchor both to real time instead. const now_ms: f64 = @floatFromInt(std.time.milliTimestamp()); const next_ms = (this.parsed.next(this.global, now_ms) catch return null) orelse return null; const delta: i64 = @intFromFloat(@max(1.0, next_ms - now_ms)); - return bun.timespec.msFromNow(.allow_mocked_time, delta); + return bun.timespec.msFromNow(.force_real_time, delta); } fn scheduleNext(this: *CronJob, vm: *jsc.VirtualMachine) void { @@ -989,6 +992,9 @@ pub const CronJob = struct { const args = callframe.arguments(); var this: *CronJob = args[args.len - 1].asPromisePtr(CronJob); defer this.deref(); + // stop() / --hot reload / worker exit released pending_promise; the + // user cancelled the job, so swallow the in-flight rejection. + if (this.stopped) return .js_undefined; const vm = this.global.bunVM(); const err = if (args.len > 0) args[0] else .js_undefined; const promise_value = this.pending_promise.get() orelse .js_undefined; diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index 979625814ee3..7da70bbaa3fa 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -215,6 +215,29 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { expect(exitCode).toBe(0); }, 70_000); + test("stop() while async callback pending suppresses unhandledRejection", async () => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + process.on("unhandledRejection", () => { console.log("LEAKED"); process.exit(1); }); + const job = Bun.cron("* * * * *", async () => { + setTimeout(() => { console.log("ok"); process.exit(0); }, 100); + job.stop(); + await Bun.sleep(10); + throw new Error("after-stop"); + }); + `, + ], + env: bunEnv, + stderr: "pipe", + }); + const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stdout.trim()).toBe("ok"); + expect(exitCode).toBe(0); + }, 70_000); + test("unhandled cron error exits process like setTimeout does", async () => { await using proc = Bun.spawn({ cmd: [ From ec0d8eedf4f8ad8e0972102885561b2b306f8686 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 15:21:22 -0700 Subject: [PATCH 14/58] Move cron jobs list to per-VM RareData Drops the process-global jobs_list/jobs_lock. Each VM owns its list on RareData (alongside hot_map), so no mutex, no vm-pointer filtering, and no stale-pointer risk when a worker terminates. --- src/bun.js/api/cron.zig | 44 ++++++++-------------------------------- src/bun.js/rare_data.zig | 1 + 2 files changed, 10 insertions(+), 35 deletions(-) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index ae9d1581453b..a08bdb39fa18 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -843,16 +843,6 @@ pub const CronJob = struct { this_value: jsc.JSRef = jsc.JSRef.empty(), stopped: bool = false, - // All live in-process cron jobs across all VMs. clearAllForVM linear-scans - // this; an app has at most a handful of cron jobs so a hash map is overkill. - var jobs_list: std.ArrayListUnmanaged(*CronJob) = .{}; - var jobs_lock: bun.Mutex = .{}; - - fn removeFromListLocked(this: *CronJob) void { - if (std.mem.indexOfScalar(*CronJob, jobs_list.items, this)) |i| - _ = jobs_list.swapRemove(i); - } - fn stopInternal(this: *CronJob, vm: *jsc.VirtualMachine) void { if (this.stopped) return; this.stopped = true; @@ -862,33 +852,21 @@ pub const CronJob = struct { this.cleanupAfterStop(vm); } - /// Removes from jobs_list before stopping so GC of the JS wrapper doesn't - /// leave a dangling pointer for clearAllForVM to read. fn selfStop(this: *CronJob, vm: *jsc.VirtualMachine) void { - { - jobs_lock.lock(); - defer jobs_lock.unlock(); - this.removeFromListLocked(); + if (vm.rare_data) |rare| { + if (std.mem.indexOfScalar(*CronJob, rare.cron_jobs.items, this)) |i| + _ = rare.cron_jobs.swapRemove(i); } this.stopInternal(vm); } /// Called from VirtualMachine.reload() before --hot re-evaluates the - /// module graph. Every Bun.cron() call still in the source will - /// re-register; deleted ones won't, so no ghost jobs survive an edit. + /// module graph, and from WebWorker.exitAndDeinit(). Every Bun.cron() + /// call still in the source will re-register on reload. pub fn clearAllForVM(vm: *jsc.VirtualMachine) void { - jobs_lock.lock(); - defer jobs_lock.unlock(); - var i: usize = 0; - while (i < jobs_list.items.len) { - const job = jobs_list.items[i]; - if (job.global.bunVM() == vm) { - job.stopInternal(vm); - _ = jobs_list.swapRemove(i); - } else { - i += 1; - } - } + const rare = vm.rare_data orelse return; + for (rare.cron_jobs.items) |job| job.stopInternal(vm); + rare.cron_jobs.clearRetainingCapacity(); } fn deinit(this: *CronJob) void { @@ -1050,11 +1028,7 @@ pub const CronJob = struct { return globalObject.throwInvalidArguments("Cron expression '{s}' has no future occurrences", .{schedule_slice.slice()}); }; - { - jobs_lock.lock(); - defer jobs_lock.unlock(); - bun.handleOom(jobs_list.append(bun.default_allocator, job)); - } + bun.handleOom(vm.rareData().cron_jobs.append(bun.default_allocator, job)); const js_value = job.toJS(globalObject); job.this_value.setStrong(js_value, globalObject); diff --git a/src/bun.js/rare_data.zig b/src/bun.js/rare_data.zig index 697300bc0866..17f0198a3db4 100644 --- a/src/bun.js/rare_data.zig +++ b/src/bun.js/rare_data.zig @@ -13,6 +13,7 @@ postgresql_context: bun.api.Postgres.PostgresSQLContext = .{}, entropy_cache: ?*EntropyCache = null, hot_map: ?HotMap = null, +cron_jobs: std.ArrayListUnmanaged(*bun.api.cron.CronJob) = .{}, // TODO: make this per JSGlobalObject instead of global // This does not handle ShadowRealm correctly! From 520ff90fa1ce8a16d93aebe4b13df84b61bff0fe Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 15:33:05 -0700 Subject: [PATCH 15/58] Address review: ref/deref bracket in onTimerFire, pass job as this - Bracket onTimerFire with ref()/deref() so stop()+GC inside the callback can't destroy the struct mid-fire (matches TimerObjectInternals) - Use this_value.finalize() instead of manual .finalized assignment - Pass the CronJob as the callback's this (matches setInterval) --- packages/bun-types/bun.d.ts | 2 +- src/bun.js/api/cron.zig | 10 ++++++++-- test/js/bun/cron/in-process-cron.test.ts | 5 ++++- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index f1f9d47b70dc..5e570f6f6413 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7492,7 +7492,7 @@ declare module "bun" { * @see {@link CronJob} for the returned handle. * @see {@link Bun.cron.parse} to preview the next fire time. */ - (schedule: CronWithAutocomplete, handler: () => MaybePromise<void>): CronJob; + (schedule: CronWithAutocomplete, handler: (this: CronJob) => MaybePromise<void>): CronJob; /** * Register an **OS-level** cron job that runs a JavaScript/TypeScript module on a schedule. * diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index a08bdb39fa18..d3474adaf888 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -878,7 +878,7 @@ pub const CronJob = struct { } pub fn finalize(this: *CronJob) void { - this.this_value = .{ .finalized = {} }; + this.this_value.finalize(); this.deref(); } @@ -909,6 +909,11 @@ pub const CronJob = struct { pub fn onTimerFire(this: *CronJob, vm: *jsc.VirtualMachine) void { this.event_loop_timer.state = .FIRED; + // Keep the struct alive across the user callback — stop() inside the + // callback downgrades this_value, and a GC could otherwise finalize + + // destroy `this` before we read fields below. + this.ref(); + defer this.deref(); if (this.stopped) return; if (vm.scriptExecutionStatus() != .running) { @@ -920,11 +925,12 @@ pub const CronJob = struct { this.selfStop(vm); return; }; + const js_this = this.this_value.tryGet() orelse .js_undefined; vm.eventLoop().enter(); defer vm.eventLoop().exit(); - const result = cb.call(this.global, .js_undefined, &.{}) catch { + const result = cb.call(this.global, js_this, &.{}) catch { if (this.global.tryTakeException()) |err| _ = vm.uncaughtException(vm.global, err, false); this.scheduleNext(vm); diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index 7da70bbaa3fa..ec225b50c76c 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -136,15 +136,18 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { // The cron expression "* * * * *" fires at the top of every minute. test("callback fires at minute boundary", async () => { let fired = 0; + let thisInCallback: unknown; const { promise, resolve } = Promise.withResolvers<void>(); - using job = Bun.cron("* * * * *", () => { + using job = Bun.cron("* * * * *", function () { fired++; + thisInCallback = this; resolve(); }); await promise; expect(fired).toBe(1); + expect(thisInCallback).toBe(job); }, 70_000); test("async callback delays next scheduling", async () => { From 8246306d3fd9b4637151998563a7f803366fcee8 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 16:08:07 -0700 Subject: [PATCH 16/58] Exclude CronJob from fake timers; release callback on stop; bun.String for expression - allowFakeTimers() returns false for .CronJob so jest.runAllTimers() can't fire cron (deadline was already .force_real_time but heap routing wasn't) - stopInternal releases callback Strong alongside pending_promise - expression is now a bun.String dupeRef instead of byte-dupe; getCron returns the existing string with no new allocation --- src/bun.js/api/Timer/EventLoopTimer.zig | 1 + src/bun.js/api/cron.zig | 9 +++++---- test/js/bun/cron/in-process-cron.test.ts | 16 +++++++++++++++- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/bun.js/api/Timer/EventLoopTimer.zig b/src/bun.js/api/Timer/EventLoopTimer.zig index 680f69cd92d9..a9f449ff50db 100644 --- a/src/bun.js/api/Timer/EventLoopTimer.zig +++ b/src/bun.js/api/Timer/EventLoopTimer.zig @@ -106,6 +106,7 @@ pub const Tag = enum { .BunTest, // for test timeouts .EventLoopDelayMonitor, // probably important .StatWatcherScheduler, + .CronJob, // calendar-anchored to real wall clock => false, else => true, }; diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index d3474adaf888..04517a9bfe6d 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -838,7 +838,7 @@ pub const CronJob = struct { pending_promise: jsc.Strong.Optional = .empty, global: *jsc.JSGlobalObject, parsed: CronExpression, - expression: []const u8, + expression: bun.String, poll: bun.Async.KeepAlive = .{}, this_value: jsc.JSRef = jsc.JSRef.empty(), stopped: bool = false, @@ -848,6 +848,7 @@ pub const CronJob = struct { this.stopped = true; if (this.event_loop_timer.state == .ACTIVE) vm.timer.remove(&this.event_loop_timer); + this.callback.deinit(); this.pending_promise.deinit(); this.cleanupAfterStop(vm); } @@ -873,7 +874,7 @@ pub const CronJob = struct { this.callback.deinit(); this.pending_promise.deinit(); this.this_value.deinit(); - bun.default_allocator.free(this.expression); + this.expression.deref(); bun.destroy(this); } @@ -1004,7 +1005,7 @@ pub const CronJob = struct { } pub fn getCron(this: *CronJob, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { - return bun.String.createUTF8ForJS(globalObject, this.expression); + return this.expression.toJS(globalObject); } pub fn register(globalObject: *jsc.JSGlobalObject, schedule_arg: jsc.JSValue, callback_arg: jsc.JSValue) bun.JSError!jsc.JSValue { @@ -1025,7 +1026,7 @@ pub const CronJob = struct { .ref_count = .init(), .global = globalObject, .parsed = parsed, - .expression = bun.handleOom(bun.default_allocator.dupe(u8, schedule_slice.slice())), + .expression = schedule_str.dupeRef(), }); job.callback = .create(callback_arg, globalObject); diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index ec225b50c76c..4a4fd9204e5f 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, jest, test } from "bun:test"; import { bunEnv, bunExe, normalizeBunSnapshot, tempDir } from "harness"; import { join } from "node:path"; @@ -121,6 +121,20 @@ describe("Bun.cron (in-process)", () => { expect(exitCode).toBe(0); }); + test("ignores jest fake timers (calendar-anchored to real time)", () => { + jest.useFakeTimers(); + try { + let fires = 0; + using job = Bun.cron("* * * * *", () => void fires++); + jest.runAllTimers(); + jest.advanceTimersByTime(120_000); + jest.runAllTimers(); + expect(fires).toBe(0); + } finally { + jest.useRealTimers(); + } + }); + test("distinguishes callback overload from OS-level overload", () => { // Callable 2nd arg → in-process; 3-string-arg → OS-level. // We only verify the callback path here; the string path is covered elsewhere. From cb6adcee798c5283d4afe0ce25b5aee3e0ee4bea Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 16:16:33 -0700 Subject: [PATCH 17/58] docs: add in-process Bun.cron(schedule, handler) section --- docs/runtime/cron.mdx | 87 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 84 insertions(+), 3 deletions(-) diff --git a/docs/runtime/cron.mdx b/docs/runtime/cron.mdx index 1a6f516c95b1..50dbcf1541b1 100644 --- a/docs/runtime/cron.mdx +++ b/docs/runtime/cron.mdx @@ -3,10 +3,18 @@ title: Cron description: Schedule and parse cron jobs with Bun --- -Bun has built-in support for registering OS-level cron jobs and parsing cron expressions. +Bun has built-in support for cron — parse expressions, run a callback on a schedule inside your process, or register OS-level jobs that survive restarts. ## Quickstart +**Run a callback on a schedule in the current process:** + +```ts +Bun.cron("0 * * * *", async () => { + await cleanupTempFiles(); +}); +``` + **Parse a cron expression to find the next matching time:** ```ts @@ -15,7 +23,7 @@ const next = Bun.cron.parse("30 9 * * MON-FRI"); console.log(next); // => 2025-01-20T09:30:00.000Z ``` -**Register a cron job that runs a script on a schedule:** +**Register an OS-level cron job that runs a script on a schedule:** ```ts await Bun.cron("./worker.ts", "30 2 * * MON", "weekly-report"); @@ -124,7 +132,80 @@ When only one is specified (the other is `*`), only that field is used for match --- -## `Bun.cron()` +## `Bun.cron(schedule, handler)` — in-process + +Run a callback on a cron schedule inside the current process. + +```ts +const job = Bun.cron("*/5 * * * *", async () => { + await syncToDatabase(); +}); +``` + +This is the lightweight option for long-running servers and workers — no system cron daemon required, works the same on every platform, and shares state (database pools, caches, module-level variables) between invocations. + +| | In-process | [OS-level](#bun-cron-path-schedule-title-os-level) | +| ---------------------------- | -------------------------------- | -------------------------------------------------- | +| Survives process exit/reboot | No | Yes | +| Shared state between runs | Yes | No (fresh process each time) | +| Platform requirements | None | crontab / launchd / Task Scheduler | +| Windows expression limits | None | [48-trigger cap](#trigger-limit) | +| Return type | [`CronJob`](#the-cronjob-handle) | `Promise<void>` | + +### Parameters + +| Parameter | Type | Description | +| ---------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------- | +| `schedule` | `string` | A [cron expression](#cron-expression-syntax) or nickname like `"@hourly"`. | +| `handler` | `(this: CronJob) => void \| Promise<void>` | Called on each fire. Inside a `function` callback, `this` is the `CronJob` (so `this.stop()` works). | + +Returns a [`CronJob`](#the-cronjob-handle) synchronously. Throws a `TypeError` if the expression is invalid or has no future occurrences (e.g. `"0 0 30 2 *"` — February 30th). + +### No-overlap guarantee + +The next fire time is computed only after the handler — including any returned `Promise` — settles. If your handler takes 90 seconds and the schedule is `* * * * *`, the second fire is the first minute boundary _after_ the handler finishes, not 60 seconds after the first fire. Invocations never stack. + +### Error handling + +Errors match `setTimeout` semantics: + +- A synchronous `throw` emits `process.on("uncaughtException")`. +- A rejected returned `Promise` emits `process.on("unhandledRejection")`. + +Without a listener, the process exits with code `1`. With a listener, the job keeps running — it does not stop on the first failure. + +```ts +process.on("unhandledRejection", err => log.error("cron failed:", err)); + +Bun.cron("* * * * *", async () => { + await mightThrow(); // logged and retried next minute +}); +``` + +### `bun --hot` + +Under `bun --hot`, all in-process cron jobs are stopped immediately before the module graph re-evaluates. Every `Bun.cron()` call still in your source then re-registers. Editing the schedule, editing the handler, or deleting the line entirely all take effect on save without leaking timers. + +### The `CronJob` handle + +```ts +using job = Bun.cron("0 * * * *", () => {}); + +job.cron; // => "0 * * * *" +job.stop(); // cancel — the handler will not fire again +job.unref(); // allow the process to exit even while scheduled +job.ref(); // keep the process alive (default) +``` + +`CronJob` is [`Disposable`](https://github.com/tc39/proposal-explicit-resource-management) — `using job = Bun.cron(...)` auto-stops at scope exit. `stop()`, `ref()`, and `unref()` all return the job for chaining. + +### Fake timers + +In-process cron is anchored to the real wall clock. `jest.useFakeTimers()`, `setSystemTime()`, `advanceTimersByTime()`, and `runAllTimers()` do not affect when it fires. + +--- + +## `Bun.cron(path, schedule, title)` — OS-level Register an OS-level cron job that runs a JavaScript/TypeScript module on a schedule. From f71fc85379f08a9753712244005c4171164e68ab Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 16:31:11 -0700 Subject: [PATCH 18/58] Store callback and pendingPromise as WriteBarrier values, rename poll_ref MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit callback and pendingPromise are now values:[] slots on the JS wrapper (matching TimeoutObject) instead of separate Strong roots — lifetime ties to the wrapper, no manual deinit on every path. poll renamed to poll_ref for consistency. --- src/bun.js/api/cron.classes.ts | 1 + src/bun.js/api/cron.zig | 49 +++++++++++++++++++--------------- 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/src/bun.js/api/cron.classes.ts b/src/bun.js/api/cron.classes.ts index ec34c8153c6b..5925d5b073de 100644 --- a/src/bun.js/api/cron.classes.ts +++ b/src/bun.js/api/cron.classes.ts @@ -31,5 +31,6 @@ export default [ cache: true, }, }, + values: ["callback", "pendingPromise"], }), ]; diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 04517a9bfe6d..9519503c0b4e 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -834,12 +834,10 @@ pub const CronJob = struct { ref_count: RefCount, event_loop_timer: EventLoopTimer = .{ .tag = .CronJob, .next = .epoch }, - callback: jsc.Strong.Optional = .empty, - pending_promise: jsc.Strong.Optional = .empty, global: *jsc.JSGlobalObject, parsed: CronExpression, expression: bun.String, - poll: bun.Async.KeepAlive = .{}, + poll_ref: bun.Async.KeepAlive = .{}, this_value: jsc.JSRef = jsc.JSRef.empty(), stopped: bool = false, @@ -848,8 +846,10 @@ pub const CronJob = struct { this.stopped = true; if (this.event_loop_timer.state == .ACTIVE) vm.timer.remove(&this.event_loop_timer); - this.callback.deinit(); - this.pending_promise.deinit(); + if (this.this_value.tryGet()) |js_value| { + js.callbackSetCached(js_value, this.global, .js_undefined); + js.pendingPromiseSetCached(js_value, this.global, .js_undefined); + } this.cleanupAfterStop(vm); } @@ -871,8 +871,6 @@ pub const CronJob = struct { } fn deinit(this: *CronJob) void { - this.callback.deinit(); - this.pending_promise.deinit(); this.this_value.deinit(); this.expression.deref(); bun.destroy(this); @@ -903,7 +901,7 @@ pub const CronJob = struct { } fn cleanupAfterStop(this: *CronJob, vm: *jsc.VirtualMachine) void { - this.poll.unref(vm); + this.poll_ref.unref(vm); if (this.this_value != .finalized) this.this_value.downgrade(); } @@ -922,11 +920,18 @@ pub const CronJob = struct { return; } - const cb = this.callback.get() orelse { + const js_this = this.this_value.tryGet() orelse { + this.selfStop(vm); + return; + }; + const cb = js.callbackGetCached(js_this) orelse { this.selfStop(vm); return; }; - const js_this = this.this_value.tryGet() orelse .js_undefined; + if (cb.isUndefined()) { + this.selfStop(vm); + return; + } vm.eventLoop().enter(); defer vm.eventLoop().exit(); @@ -942,9 +947,9 @@ pub const CronJob = struct { switch (promise.status()) { .pending => { this.ref(); - this.pending_promise.set(this.global, result); + js.pendingPromiseSetCached(js_this, this.global, result); result.then(this.global, this, onPromiseResolve, onPromiseReject) catch { - this.pending_promise.deinit(); + js.pendingPromiseSetCached(js_this, this.global, .js_undefined); this.deref(); this.scheduleNext(vm); }; @@ -968,7 +973,8 @@ pub const CronJob = struct { const args = callframe.arguments(); var this: *CronJob = args[args.len - 1].asPromisePtr(CronJob); defer this.deref(); - this.pending_promise.deinit(); + if (this.this_value.tryGet()) |js_this| + js.pendingPromiseSetCached(js_this, this.global, .js_undefined); this.scheduleNext(this.global.bunVM()); return .js_undefined; } @@ -977,13 +983,14 @@ pub const CronJob = struct { const args = callframe.arguments(); var this: *CronJob = args[args.len - 1].asPromisePtr(CronJob); defer this.deref(); - // stop() / --hot reload / worker exit released pending_promise; the - // user cancelled the job, so swallow the in-flight rejection. + // stop() / --hot reload / worker exit cleared pendingPromise; the user + // cancelled the job, so swallow the in-flight rejection. if (this.stopped) return .js_undefined; const vm = this.global.bunVM(); const err = if (args.len > 0) args[0] else .js_undefined; - const promise_value = this.pending_promise.get() orelse .js_undefined; - this.pending_promise.deinit(); + const js_this = this.this_value.tryGet() orelse return .js_undefined; + const promise_value = js.pendingPromiseGetCached(js_this) orelse .js_undefined; + js.pendingPromiseSetCached(js_this, this.global, .js_undefined); vm.unhandledRejection(vm.global, err, promise_value); this.scheduleNext(vm); return .js_undefined; @@ -995,12 +1002,12 @@ pub const CronJob = struct { } pub fn doRef(this: *CronJob, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { - if (!this.stopped) this.poll.ref(this.global.bunVM()); + if (!this.stopped) this.poll_ref.ref(this.global.bunVM()); return callframe.this(); } pub fn doUnref(this: *CronJob, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { - this.poll.unref(this.global.bunVM()); + this.poll_ref.unref(this.global.bunVM()); return callframe.this(); } @@ -1028,7 +1035,6 @@ pub const CronJob = struct { .parsed = parsed, .expression = schedule_str.dupeRef(), }); - job.callback = .create(callback_arg, globalObject); const next_time = job.computeNextTimespec() orelse { job.deref(); @@ -1039,8 +1045,9 @@ pub const CronJob = struct { const js_value = job.toJS(globalObject); job.this_value.setStrong(js_value, globalObject); + js.callbackSetCached(js_value, globalObject, callback_arg); - job.poll.ref(vm); + job.poll_ref.ref(vm); vm.timer.update(&job.event_loop_timer, &next_time); return js_value; From 080ccc3fb20077c955ccb546b786a60da707ea20 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 16:42:34 -0700 Subject: [PATCH 19/58] Support fake timers in Bun.cron; address Jarred review - computeNextTimespec reads mocked Date.now() under fake timers via FakeTimers.dateNowMs(); deadline uses .allow_mocked_time so setSystemTime + advanceTimersByTime drive cron deterministically - Fix setSystemTime/advanceTimersByTime integration: setSystemTime now updates FakeTimers.date_now_offset so a later advance continues from the set value instead of reverting to the useFakeTimers() snapshot - Drop expression field; cron cache pre-set with input JSValue, getCron returns undefined (cache-first wrapper makes it unreachable) - Wrap callback with withAsyncContextIfNeeded for AsyncLocalStorage - cron_jobs list entry holds a refcount; deref on remove - Convert in-process firing tests to fake timers (instant) --- docs/runtime/cron.mdx | 19 ++++- src/bun.js/api/Timer/EventLoopTimer.zig | 1 - src/bun.js/api/cron.zig | 31 ++++---- src/bun.js/bindings/JSMockFunction.cpp | 5 ++ src/bun.js/test/timers/FakeTimers.zig | 16 ++++ test/js/bun/cron/in-process-cron.test.ts | 98 +++++++++++++----------- 6 files changed, 111 insertions(+), 59 deletions(-) diff --git a/docs/runtime/cron.mdx b/docs/runtime/cron.mdx index 50dbcf1541b1..b1b0f9ac8e7d 100644 --- a/docs/runtime/cron.mdx +++ b/docs/runtime/cron.mdx @@ -199,9 +199,24 @@ job.ref(); // keep the process alive (default) `CronJob` is [`Disposable`](https://github.com/tc39/proposal-explicit-resource-management) — `using job = Bun.cron(...)` auto-stops at scope exit. `stop()`, `ref()`, and `unref()` all return the job for chaining. -### Fake timers +### Testing with fake timers -In-process cron is anchored to the real wall clock. `jest.useFakeTimers()`, `setSystemTime()`, `advanceTimersByTime()`, and `runAllTimers()` do not affect when it fires. +In-process cron respects `bun:test` fake timers. The schedule is computed against the mocked `Date.now()`, so you can drive fires deterministically: + +```ts +import { jest } from "bun:test"; + +jest.useFakeTimers(); +jest.setSystemTime(new Date("2025-01-01T23:59:30Z")); + +const handler = jest.fn(); +Bun.cron("0 0 * * *", handler); + +jest.advanceTimersByTime(30_000); // → 2025-01-02T00:00:00Z +expect(handler).toHaveBeenCalledTimes(1); +``` + +Without fake timers, cron fires on the real wall clock. --- diff --git a/src/bun.js/api/Timer/EventLoopTimer.zig b/src/bun.js/api/Timer/EventLoopTimer.zig index a9f449ff50db..680f69cd92d9 100644 --- a/src/bun.js/api/Timer/EventLoopTimer.zig +++ b/src/bun.js/api/Timer/EventLoopTimer.zig @@ -106,7 +106,6 @@ pub const Tag = enum { .BunTest, // for test timeouts .EventLoopDelayMonitor, // probably important .StatWatcherScheduler, - .CronJob, // calendar-anchored to real wall clock => false, else => true, }; diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 9519503c0b4e..821ecb8ee12e 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -836,7 +836,6 @@ pub const CronJob = struct { event_loop_timer: EventLoopTimer = .{ .tag = .CronJob, .next = .epoch }, global: *jsc.JSGlobalObject, parsed: CronExpression, - expression: bun.String, poll_ref: bun.Async.KeepAlive = .{}, this_value: jsc.JSRef = jsc.JSRef.empty(), stopped: bool = false, @@ -855,8 +854,10 @@ pub const CronJob = struct { fn selfStop(this: *CronJob, vm: *jsc.VirtualMachine) void { if (vm.rare_data) |rare| { - if (std.mem.indexOfScalar(*CronJob, rare.cron_jobs.items, this)) |i| + if (std.mem.indexOfScalar(*CronJob, rare.cron_jobs.items, this)) |i| { _ = rare.cron_jobs.swapRemove(i); + this.deref(); + } } this.stopInternal(vm); } @@ -866,13 +867,15 @@ pub const CronJob = struct { /// call still in the source will re-register on reload. pub fn clearAllForVM(vm: *jsc.VirtualMachine) void { const rare = vm.rare_data orelse return; - for (rare.cron_jobs.items) |job| job.stopInternal(vm); + for (rare.cron_jobs.items) |job| { + job.stopInternal(vm); + job.deref(); + } rare.cron_jobs.clearRetainingCapacity(); } fn deinit(this: *CronJob) void { this.this_value.deinit(); - this.expression.deref(); bun.destroy(this); } @@ -882,13 +885,14 @@ pub const CronJob = struct { } fn computeNextTimespec(this: *CronJob) ?bun.timespec { - // Cron occurrences are calendar-based (real epoch); the timer heap is - // monotonic. Using .allow_mocked_time here would mix the two timebases - // under fake timers — anchor both to real time instead. - const now_ms: f64 = @floatFromInt(std.time.milliTimestamp()); + // Cron occurrences are calendar-based, so the input must be epoch ms. + // Under fake timers that's the mocked Date.now(); the deadline then + // uses .allow_mocked_time so both halves track the same fake clock. + const now_ms: f64 = bun.jsc.Jest.bun_test.FakeTimers.current_time.dateNowMs() orelse + @floatFromInt(std.time.milliTimestamp()); const next_ms = (this.parsed.next(this.global, now_ms) catch return null) orelse return null; const delta: i64 = @intFromFloat(@max(1.0, next_ms - now_ms)); - return bun.timespec.msFromNow(.force_real_time, delta); + return bun.timespec.msFromNow(.allow_mocked_time, delta); } fn scheduleNext(this: *CronJob, vm: *jsc.VirtualMachine) void { @@ -1011,8 +1015,8 @@ pub const CronJob = struct { return callframe.this(); } - pub fn getCron(this: *CronJob, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { - return this.expression.toJS(globalObject); + pub fn getCron(_: *CronJob, _: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + return .js_undefined; // unreachable — register() pre-populates the cache via cronSetCached } pub fn register(globalObject: *jsc.JSGlobalObject, schedule_arg: jsc.JSValue, callback_arg: jsc.JSValue) bun.JSError!jsc.JSValue { @@ -1033,7 +1037,6 @@ pub const CronJob = struct { .ref_count = .init(), .global = globalObject, .parsed = parsed, - .expression = schedule_str.dupeRef(), }); const next_time = job.computeNextTimespec() orelse { @@ -1041,11 +1044,13 @@ pub const CronJob = struct { return globalObject.throwInvalidArguments("Cron expression '{s}' has no future occurrences", .{schedule_slice.slice()}); }; + job.ref(); // owned by cron_jobs entry bun.handleOom(vm.rareData().cron_jobs.append(bun.default_allocator, job)); const js_value = job.toJS(globalObject); job.this_value.setStrong(js_value, globalObject); - js.callbackSetCached(js_value, globalObject, callback_arg); + js.cronSetCached(js_value, globalObject, schedule_arg); + js.callbackSetCached(js_value, globalObject, callback_arg.withAsyncContextIfNeeded(globalObject)); job.poll_ref.ref(vm); vm.timer.update(&job.event_loop_timer, &next_time); diff --git a/src/bun.js/bindings/JSMockFunction.cpp b/src/bun.js/bindings/JSMockFunction.cpp index 1c760357186a..3b3216b9fa29 100644 --- a/src/bun.js/bindings/JSMockFunction.cpp +++ b/src/bun.js/bindings/JSMockFunction.cpp @@ -1447,6 +1447,8 @@ BUN_DEFINE_HOST_FUNCTION(JSMock__jsNow, (JSC::JSGlobalObject * globalObject, JSC { return JSValue::encode(jsNumber(globalObject->jsDateNow())); } +extern "C" void Bun__FakeTimers__onSetSystemTime(double jsEpochMs); + BUN_DEFINE_HOST_FUNCTION(JSMock__jsSetSystemTime, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callframe)) { JSValue argument0 = callframe->argument(0); @@ -1454,11 +1456,14 @@ BUN_DEFINE_HOST_FUNCTION(JSMock__jsSetSystemTime, (JSC::JSGlobalObject * globalO if (auto* dateInstance = jsDynamicCast<DateInstance*>(argument0)) { if (std::isnormal(dateInstance->internalNumber())) { globalObject->overridenDateNow = dateInstance->internalNumber(); + Bun__FakeTimers__onSetSystemTime(dateInstance->internalNumber()); } return JSValue::encode(callframe->thisValue()); } // number > 0 is a valid date otherwise it's invalid and we should reset the time (set to -1) globalObject->overridenDateNow = (argument0.isNumber() && argument0.asNumber() >= 0) ? argument0.asNumber() : -1; + if (globalObject->overridenDateNow >= 0) + Bun__FakeTimers__onSetSystemTime(globalObject->overridenDateNow); return JSValue::encode(callframe->thisValue()); } diff --git a/src/bun.js/test/timers/FakeTimers.zig b/src/bun.js/test/timers/FakeTimers.zig index 4caf05d62488..f4aa2db71074 100644 --- a/src/bun.js/test/timers/FakeTimers.zig +++ b/src/bun.js/test/timers/FakeTimers.zig @@ -18,6 +18,18 @@ pub var current_time: struct { if (value.eql(&min_timespec)) return null; return value; } + /// Mocked epoch milliseconds (what JS Date.now() returns under fake timers). + pub fn dateNowMs(this: *@This()) ?f64 { + const ts = this.getTimespecNow() orelse return null; + return this.date_now_offset + @as(f64, @floatFromInt(ts.ms())); + } + /// Called from JSMock__jsSetSystemTime so that a subsequent + /// advanceTimersByTime() continues from the value setSystemTime set + /// instead of reverting to the offset captured at useFakeTimers(). + pub fn onSetSystemTime(this: *@This(), js_epoch_ms: f64) void { + const ts = this.getTimespecNow() orelse return; + this.date_now_offset = js_epoch_ms - @as(f64, @floatFromInt(ts.ms())); + } pub fn set(this: *@This(), globalObject: *jsc.JSGlobalObject, v: struct { offset: *const bun.timespec, js: ?f64 = null, @@ -366,6 +378,10 @@ pub fn putTimersFns(globalObject: *jsc.JSGlobalObject, jest: jsc.JSValue, vi: js } } +pub export fn Bun__FakeTimers__onSetSystemTime(js_epoch_ms: f64) void { + current_time.onSetSystemTime(js_epoch_ms); +} + const bindgen_generated = @import("bindgen_generated"); const std = @import("std"); diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index 4a4fd9204e5f..243611e53e7a 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -121,15 +121,18 @@ describe("Bun.cron (in-process)", () => { expect(exitCode).toBe(0); }); - test("ignores jest fake timers (calendar-anchored to real time)", () => { + test("respects jest fake timers via mocked Date.now()", () => { jest.useFakeTimers(); try { + jest.setSystemTime(new Date("2025-01-01T23:59:30Z")); let fires = 0; - using job = Bun.cron("* * * * *", () => void fires++); - jest.runAllTimers(); - jest.advanceTimersByTime(120_000); - jest.runAllTimers(); + using job = Bun.cron("0 0 * * *", () => void fires++); + jest.advanceTimersByTime(29_000); expect(fires).toBe(0); + jest.advanceTimersByTime(2_000); + expect(fires).toBe(1); + jest.advanceTimersByTime(24 * 60 * 60_000); + expect(fires).toBe(2); } finally { jest.useRealTimers(); } @@ -145,46 +148,55 @@ describe("Bun.cron (in-process)", () => { }); }); -describe.concurrent("Bun.cron (in-process) — firing", () => { - // This test waits for a real cron fire, which takes up to 60 seconds. - // The cron expression "* * * * *" fires at the top of every minute. - test("callback fires at minute boundary", async () => { - let fired = 0; - let thisInCallback: unknown; - const { promise, resolve } = Promise.withResolvers<void>(); - - using job = Bun.cron("* * * * *", function () { - fired++; - thisInCallback = this; - resolve(); - }); - - await promise; - expect(fired).toBe(1); - expect(thisInCallback).toBe(job); - }, 70_000); - - test("async callback delays next scheduling", async () => { - // The callback returns a Promise; next fire is scheduled only after it resolves. - // We can't easily observe the timing without waiting 2+ minutes, so we just - // verify no crash and that stop() during the pending promise works. - const handler = Promise.withResolvers<void>(); - const fire = Promise.withResolvers<void>(); - - using job = Bun.cron("* * * * *", async () => { - fire.resolve(); - await handler.promise; - }); +describe("Bun.cron (in-process) — firing (fake timers)", () => { + test("callback fires at minute boundary, this === job", () => { + jest.useFakeTimers(); + try { + jest.setSystemTime(new Date("2025-01-01T00:00:30Z")); + let fired = 0; + let thisInCallback: unknown; + using job = Bun.cron("* * * * *", function () { + fired++; + thisInCallback = this; + }); + jest.advanceTimersByTime(30_000); + expect(fired).toBe(1); + expect(thisInCallback).toBe(job); + jest.advanceTimersByTime(60_000); + expect(fired).toBe(2); + } finally { + jest.useRealTimers(); + } + }); - await fire.promise; - // Handler is now awaiting; stop while it's pending - job.stop(); - // Let the handler complete - handler.resolve(); - await Bun.sleep(10); - // No crash, no second fire - }, 70_000); + test("async callback delays next scheduling (no overlap)", async () => { + jest.useFakeTimers(); + try { + jest.setSystemTime(new Date("2025-01-01T00:00:59Z")); + let starts = 0; + const handler = Promise.withResolvers<void>(); + using job = Bun.cron("* * * * *", async () => { + starts++; + await handler.promise; + }); + jest.advanceTimersByTime(1_000); + expect(starts).toBe(1); + // Handler still pending — advancing past 5 more boundaries must not stack fires. + jest.advanceTimersByTime(5 * 60_000); + expect(starts).toBe(1); + handler.resolve(); + // Drain the .then() chain so onPromiseResolve runs and reschedules. + for (let i = 0; i < 3; i++) await Promise.resolve(); + // Next fire scheduled from current fake time; one more minute triggers it. + jest.advanceTimersByTime(60_000); + expect(starts).toBe(2); + } finally { + jest.useRealTimers(); + } + }); +}); +describe.concurrent("Bun.cron (in-process) — firing (subprocess)", () => { test("sync throw in callback emits uncaughtException", async () => { // Matches setTimeout: sync throw → uncaughtException. Process exits 1 without a handler. await using proc = Bun.spawn({ From 56a6d21968abfa2185f61accef6049ae00bbce0c Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 16:48:05 -0700 Subject: [PATCH 20/58] Surface rejections after stop; free cron_jobs buffer in RareData.deinit - onPromiseReject no longer suppresses when stopped (errors surface like setInterval); pendingPromise WriteBarrier slot is no longer cleared in stopInternal so the promise arg is still available - RareData.deinit() frees cron_jobs backing buffer --- src/bun.js/api/cron.zig | 15 +++++---------- src/bun.js/rare_data.zig | 1 + test/js/bun/cron/in-process-cron.test.ts | 10 ++++++---- 3 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 821ecb8ee12e..0b7f2c0fac06 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -845,10 +845,6 @@ pub const CronJob = struct { this.stopped = true; if (this.event_loop_timer.state == .ACTIVE) vm.timer.remove(&this.event_loop_timer); - if (this.this_value.tryGet()) |js_value| { - js.callbackSetCached(js_value, this.global, .js_undefined); - js.pendingPromiseSetCached(js_value, this.global, .js_undefined); - } this.cleanupAfterStop(vm); } @@ -987,14 +983,13 @@ pub const CronJob = struct { const args = callframe.arguments(); var this: *CronJob = args[args.len - 1].asPromisePtr(CronJob); defer this.deref(); - // stop() / --hot reload / worker exit cleared pendingPromise; the user - // cancelled the job, so swallow the in-flight rejection. - if (this.stopped) return .js_undefined; const vm = this.global.bunVM(); const err = if (args.len > 0) args[0] else .js_undefined; - const js_this = this.this_value.tryGet() orelse return .js_undefined; - const promise_value = js.pendingPromiseGetCached(js_this) orelse .js_undefined; - js.pendingPromiseSetCached(js_this, this.global, .js_undefined); + var promise_value: jsc.JSValue = .js_undefined; + if (this.this_value.tryGet()) |js_this| { + promise_value = js.pendingPromiseGetCached(js_this) orelse .js_undefined; + js.pendingPromiseSetCached(js_this, this.global, .js_undefined); + } vm.unhandledRejection(vm.global, err, promise_value); this.scheduleNext(vm); return .js_undefined; diff --git a/src/bun.js/rare_data.zig b/src/bun.js/rare_data.zig index 17f0198a3db4..e512b126af1d 100644 --- a/src/bun.js/rare_data.zig +++ b/src/bun.js/rare_data.zig @@ -605,6 +605,7 @@ pub fn deinit(this: *RareData) void { } this.cleanup_hooks.clearAndFree(bun.default_allocator); + this.cron_jobs.deinit(bun.default_allocator); this.path_buf.deinit(); if (this.websocket_deflate) |deflate| { diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index 243611e53e7a..677c49856738 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -244,15 +244,17 @@ describe.concurrent("Bun.cron (in-process) — firing (subprocess)", () => { expect(exitCode).toBe(0); }, 70_000); - test("stop() while async callback pending suppresses unhandledRejection", async () => { + test("stop() while async callback pending still surfaces unhandledRejection with promise", async () => { await using proc = Bun.spawn({ cmd: [ bunExe(), "-e", ` - process.on("unhandledRejection", () => { console.log("LEAKED"); process.exit(1); }); + process.on("unhandledRejection", (e, p) => { + console.log("caught=" + e.message + ":" + (p instanceof Promise)); + process.exit(0); + }); const job = Bun.cron("* * * * *", async () => { - setTimeout(() => { console.log("ok"); process.exit(0); }, 100); job.stop(); await Bun.sleep(10); throw new Error("after-stop"); @@ -263,7 +265,7 @@ describe.concurrent("Bun.cron (in-process) — firing (subprocess)", () => { stderr: "pipe", }); const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect(stdout.trim()).toBe("ok"); + expect(stdout.trim()).toBe("caught=after-stop:true"); expect(exitCode).toBe(0); }, 70_000); From 789f3cb277fea05eb01906b15e0fcf2dc9c25104 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 17:06:32 -0700 Subject: [PATCH 21/58] Reset date_now_offset when setSystemTime() is called with no args Previously a setSystemTime(X) followed by setSystemTime() reset left date_now_offset at the X-derived value, so a subsequent advanceTimersByTime jumped Date.now() back to X. The reset path now re-anchors to real time. Adds tests for setSystemTime composing with advanceTimersByTime. --- src/bun.js/bindings/JSMockFunction.cpp | 3 +-- src/bun.js/test/timers/FakeTimers.zig | 4 +++- .../bun/test/fake-timers/fake-timers.test.ts | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/bun.js/bindings/JSMockFunction.cpp b/src/bun.js/bindings/JSMockFunction.cpp index 3b3216b9fa29..12396f6e588a 100644 --- a/src/bun.js/bindings/JSMockFunction.cpp +++ b/src/bun.js/bindings/JSMockFunction.cpp @@ -1462,8 +1462,7 @@ BUN_DEFINE_HOST_FUNCTION(JSMock__jsSetSystemTime, (JSC::JSGlobalObject * globalO } // number > 0 is a valid date otherwise it's invalid and we should reset the time (set to -1) globalObject->overridenDateNow = (argument0.isNumber() && argument0.asNumber() >= 0) ? argument0.asNumber() : -1; - if (globalObject->overridenDateNow >= 0) - Bun__FakeTimers__onSetSystemTime(globalObject->overridenDateNow); + Bun__FakeTimers__onSetSystemTime(globalObject->overridenDateNow); return JSValue::encode(callframe->thisValue()); } diff --git a/src/bun.js/test/timers/FakeTimers.zig b/src/bun.js/test/timers/FakeTimers.zig index f4aa2db71074..71e96ef10237 100644 --- a/src/bun.js/test/timers/FakeTimers.zig +++ b/src/bun.js/test/timers/FakeTimers.zig @@ -379,7 +379,9 @@ pub fn putTimersFns(globalObject: *jsc.JSGlobalObject, jest: jsc.JSValue, vi: js } pub export fn Bun__FakeTimers__onSetSystemTime(js_epoch_ms: f64) void { - current_time.onSetSystemTime(js_epoch_ms); + // -1 = setSystemTime() reset; re-anchor date_now_offset to real time so + // a later advanceTimersByTime doesn't resurrect the previously-set value. + current_time.onSetSystemTime(if (js_epoch_ms < 0) @floatFromInt(std.time.milliTimestamp()) else js_epoch_ms); } const bindgen_generated = @import("bindgen_generated"); diff --git a/test/js/bun/test/fake-timers/fake-timers.test.ts b/test/js/bun/test/fake-timers/fake-timers.test.ts index 40ae5b1daae3..7049c9e14998 100644 --- a/test/js/bun/test/fake-timers/fake-timers.test.ts +++ b/test/js/bun/test/fake-timers/fake-timers.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, test, vi } from "vitest"; +import { setSystemTime } from "bun:test"; afterEach(() => vi.useRealTimers()); @@ -213,6 +214,23 @@ describe("isFakeTimers", () => { }); }); describe("Date.now() mocking", () => { + test("setSystemTime composes with advanceTimersByTime", () => { + vi.useFakeTimers(); + setSystemTime(new Date("2020-06-15T12:00:00Z")); + expect(Date.now()).toBe(new Date("2020-06-15T12:00:00Z").getTime()); + vi.advanceTimersByTime(5000); + expect(Date.now()).toBe(new Date("2020-06-15T12:00:05Z").getTime()); + }); + + test("setSystemTime() reset then advanceTimersByTime tracks real time", () => { + vi.useFakeTimers(); + setSystemTime(new Date("2020-06-15T12:00:00Z")); + setSystemTime(); // reset + const realYear = new Date().getFullYear(); + vi.advanceTimersByTime(1000); + expect(new Date().getFullYear()).toBe(realYear); + }); + test("Date.now() before and after vi.useFakeTimers() should be roughly equal", () => { const beforeFake = Date.now(); vi.useFakeTimers(); From 4807d6ccb10272b025f0d80d7fe67b824c2014ca Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Thu, 2 Apr 2026 00:08:27 +0000 Subject: [PATCH 22/58] [autofix.ci] apply automated fixes --- test/js/bun/test/fake-timers/fake-timers.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/js/bun/test/fake-timers/fake-timers.test.ts b/test/js/bun/test/fake-timers/fake-timers.test.ts index 7049c9e14998..f1d740f565c3 100644 --- a/test/js/bun/test/fake-timers/fake-timers.test.ts +++ b/test/js/bun/test/fake-timers/fake-timers.test.ts @@ -1,5 +1,5 @@ -import { afterEach, describe, expect, test, vi } from "vitest"; import { setSystemTime } from "bun:test"; +import { afterEach, describe, expect, test, vi } from "vitest"; afterEach(() => vi.useRealTimers()); From 46db23431ea23cafb7cfef8fb9d94559fdd75b4c Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 17:27:08 -0700 Subject: [PATCH 23/58] Inline single-use helpers in CronJob and trim narrative comments - Inline cleanupAfterStop into stopInternal (one caller, two lines) - Reorder selfStop: stopInternal before swapRemove+deref so the struct is still alive even if the cron_jobs entry was the last ref - Trim verbose WHAT-narrating block comments --- src/bun.js/api/cron.zig | 36 ++++++++++-------------------------- 1 file changed, 10 insertions(+), 26 deletions(-) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 0b7f2c0fac06..a2990b14dd7d 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -809,18 +809,8 @@ pub const CronRemoveJob = struct { }; // ============================================================================ -// CronJob — in-process callback-style cron (issue #7004) +// CronJob — in-process callback-style cron (Bun.cron(expr, cb)) // ============================================================================ -// -// Bun.cron("*/5 * * * *", async () => { ... }) -// -// Unlike the OS-level cron above, this runs the callback in the current -// process on the event loop. The next execution is scheduled only after the -// callback (including any returned Promise) completes, so callbacks never -// overlap. Error semantics match setTimeout: sync throws become -// uncaughtException, rejected Promises become unhandledRejection. Under --hot, -// VirtualMachine.reload() calls clearAllForVM before re-evaluating the module -// graph, so deleted Bun.cron() calls don't leave ghost timers. pub const CronJob = struct { const RefCount = bun.ptr.RefCount(@This(), "ref_count", deinit, .{}); @@ -845,22 +835,24 @@ pub const CronJob = struct { this.stopped = true; if (this.event_loop_timer.state == .ACTIVE) vm.timer.remove(&this.event_loop_timer); - this.cleanupAfterStop(vm); + this.poll_ref.unref(vm); + if (this.this_value != .finalized) + this.this_value.downgrade(); } fn selfStop(this: *CronJob, vm: *jsc.VirtualMachine) void { + this.stopInternal(vm); if (vm.rare_data) |rare| { if (std.mem.indexOfScalar(*CronJob, rare.cron_jobs.items, this)) |i| { _ = rare.cron_jobs.swapRemove(i); this.deref(); } } - this.stopInternal(vm); } /// Called from VirtualMachine.reload() before --hot re-evaluates the /// module graph, and from WebWorker.exitAndDeinit(). Every Bun.cron() - /// call still in the source will re-register on reload. + /// call still in the source re-registers on reload. pub fn clearAllForVM(vm: *jsc.VirtualMachine) void { const rare = vm.rare_data orelse return; for (rare.cron_jobs.items) |job| { @@ -881,9 +873,8 @@ pub const CronJob = struct { } fn computeNextTimespec(this: *CronJob) ?bun.timespec { - // Cron occurrences are calendar-based, so the input must be epoch ms. - // Under fake timers that's the mocked Date.now(); the deadline then - // uses .allow_mocked_time so both halves track the same fake clock. + // Use mocked Date.now() under fake timers so the deadline and the + // cron occurrence track the same clock. const now_ms: f64 = bun.jsc.Jest.bun_test.FakeTimers.current_time.dateNowMs() orelse @floatFromInt(std.time.milliTimestamp()); const next_ms = (this.parsed.next(this.global, now_ms) catch return null) orelse return null; @@ -900,17 +891,10 @@ pub const CronJob = struct { vm.timer.update(&this.event_loop_timer, &next_time); } - fn cleanupAfterStop(this: *CronJob, vm: *jsc.VirtualMachine) void { - this.poll_ref.unref(vm); - if (this.this_value != .finalized) - this.this_value.downgrade(); - } - pub fn onTimerFire(this: *CronJob, vm: *jsc.VirtualMachine) void { this.event_loop_timer.state = .FIRED; - // Keep the struct alive across the user callback — stop() inside the - // callback downgrades this_value, and a GC could otherwise finalize + - // destroy `this` before we read fields below. + // stop() inside the callback downgrades this_value; without this + // ref() a GC could finalize and destroy `this` mid-callback. this.ref(); defer this.deref(); From 8aa7e8855f91bf235c8d3a8857ced51adf8e784d Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 17:39:35 -0700 Subject: [PATCH 24/58] Revert fake-timer support for cron; balance pending ref on VM teardown Cron is anchored to real wall clock (.force_real_time, allowFakeTimers returns false). Fake-timer support and the setSystemTime/advanceTimersByTime integration are deferred to a follow-up. Adds pending_ref flag so the .then() ref is released exactly once by either the settle handler or clearAllForVM(.teardown), preventing a struct leak when a worker exits mid-await. --- docs/runtime/cron.mdx | 19 +--- src/bun.js/VirtualMachine.zig | 2 +- src/bun.js/api/Timer/EventLoopTimer.zig | 1 + src/bun.js/api/cron.zig | 36 +++++--- src/bun.js/bindings/JSMockFunction.cpp | 4 - src/bun.js/test/timers/FakeTimers.zig | 18 ---- src/bun.js/web_worker.zig | 2 +- test/js/bun/cron/in-process-cron.test.ts | 90 ++++++++----------- .../bun/test/fake-timers/fake-timers.test.ts | 18 ---- 9 files changed, 64 insertions(+), 126 deletions(-) diff --git a/docs/runtime/cron.mdx b/docs/runtime/cron.mdx index b1b0f9ac8e7d..50dbcf1541b1 100644 --- a/docs/runtime/cron.mdx +++ b/docs/runtime/cron.mdx @@ -199,24 +199,9 @@ job.ref(); // keep the process alive (default) `CronJob` is [`Disposable`](https://github.com/tc39/proposal-explicit-resource-management) — `using job = Bun.cron(...)` auto-stops at scope exit. `stop()`, `ref()`, and `unref()` all return the job for chaining. -### Testing with fake timers +### Fake timers -In-process cron respects `bun:test` fake timers. The schedule is computed against the mocked `Date.now()`, so you can drive fires deterministically: - -```ts -import { jest } from "bun:test"; - -jest.useFakeTimers(); -jest.setSystemTime(new Date("2025-01-01T23:59:30Z")); - -const handler = jest.fn(); -Bun.cron("0 0 * * *", handler); - -jest.advanceTimersByTime(30_000); // → 2025-01-02T00:00:00Z -expect(handler).toHaveBeenCalledTimes(1); -``` - -Without fake timers, cron fires on the real wall clock. +In-process cron is anchored to the real wall clock. `jest.useFakeTimers()`, `setSystemTime()`, `advanceTimersByTime()`, and `runAllTimers()` do not affect when it fires. --- diff --git a/src/bun.js/VirtualMachine.zig b/src/bun.js/VirtualMachine.zig index 5fd0661bb53a..316129cedfb2 100644 --- a/src/bun.js/VirtualMachine.zig +++ b/src/bun.js/VirtualMachine.zig @@ -746,7 +746,7 @@ pub fn reload(this: *VirtualMachine, _: *HotReloader.Task) void { Output.enableBuffering(); } - jsc.API.cron.CronJob.clearAllForVM(this); + jsc.API.cron.CronJob.clearAllForVM(this, .reload); this.global.reload() catch @panic("Failed to reload"); this.hot_reload_counter += 1; this.pending_internal_promise = this.reloadEntryPoint(this.main) catch @panic("Failed to reload"); diff --git a/src/bun.js/api/Timer/EventLoopTimer.zig b/src/bun.js/api/Timer/EventLoopTimer.zig index 680f69cd92d9..a9f449ff50db 100644 --- a/src/bun.js/api/Timer/EventLoopTimer.zig +++ b/src/bun.js/api/Timer/EventLoopTimer.zig @@ -106,6 +106,7 @@ pub const Tag = enum { .BunTest, // for test timeouts .EventLoopDelayMonitor, // probably important .StatWatcherScheduler, + .CronJob, // calendar-anchored to real wall clock => false, else => true, }; diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index a2990b14dd7d..a32d8565d46a 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -829,6 +829,16 @@ pub const CronJob = struct { poll_ref: bun.Async.KeepAlive = .{}, this_value: jsc.JSRef = jsc.JSRef.empty(), stopped: bool = false, + /// True while a ref() is held across an in-flight callback promise. + /// Released exactly once by either onPromiseResolve/Reject or stopInternal. + pending_ref: bool = false, + + fn releasePendingRef(this: *CronJob) void { + if (this.pending_ref) { + this.pending_ref = false; + this.deref(); + } + } fn stopInternal(this: *CronJob, vm: *jsc.VirtualMachine) void { if (this.stopped) return; @@ -850,13 +860,15 @@ pub const CronJob = struct { } } - /// Called from VirtualMachine.reload() before --hot re-evaluates the - /// module graph, and from WebWorker.exitAndDeinit(). Every Bun.cron() - /// call still in the source re-registers on reload. - pub fn clearAllForVM(vm: *jsc.VirtualMachine) void { + /// `.reload`: --hot — promises in flight will still settle on this VM, so + /// the pending ref is left for onPromiseResolve/Reject to balance. + /// `.teardown`: worker exit — the event loop is dying, settle never + /// happens, so release the pending ref here to avoid leaking the struct. + pub fn clearAllForVM(vm: *jsc.VirtualMachine, comptime mode: enum { reload, teardown }) void { const rare = vm.rare_data orelse return; for (rare.cron_jobs.items) |job| { job.stopInternal(vm); + if (mode == .teardown) job.releasePendingRef(); job.deref(); } rare.cron_jobs.clearRetainingCapacity(); @@ -873,13 +885,12 @@ pub const CronJob = struct { } fn computeNextTimespec(this: *CronJob) ?bun.timespec { - // Use mocked Date.now() under fake timers so the deadline and the - // cron occurrence track the same clock. - const now_ms: f64 = bun.jsc.Jest.bun_test.FakeTimers.current_time.dateNowMs() orelse - @floatFromInt(std.time.milliTimestamp()); + // Cron occurrences are calendar-based (real epoch); the timer heap is + // monotonic. Anchor both to real time so fake timers don't half-apply. + const now_ms: f64 = @floatFromInt(std.time.milliTimestamp()); const next_ms = (this.parsed.next(this.global, now_ms) catch return null) orelse return null; const delta: i64 = @intFromFloat(@max(1.0, next_ms - now_ms)); - return bun.timespec.msFromNow(.allow_mocked_time, delta); + return bun.timespec.msFromNow(.force_real_time, delta); } fn scheduleNext(this: *CronJob, vm: *jsc.VirtualMachine) void { @@ -931,10 +942,11 @@ pub const CronJob = struct { switch (promise.status()) { .pending => { this.ref(); + this.pending_ref = true; js.pendingPromiseSetCached(js_this, this.global, result); result.then(this.global, this, onPromiseResolve, onPromiseReject) catch { js.pendingPromiseSetCached(js_this, this.global, .js_undefined); - this.deref(); + this.releasePendingRef(); this.scheduleNext(vm); }; return; @@ -956,7 +968,7 @@ pub const CronJob = struct { fn onPromiseResolve(_: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args = callframe.arguments(); var this: *CronJob = args[args.len - 1].asPromisePtr(CronJob); - defer this.deref(); + defer this.releasePendingRef(); if (this.this_value.tryGet()) |js_this| js.pendingPromiseSetCached(js_this, this.global, .js_undefined); this.scheduleNext(this.global.bunVM()); @@ -966,7 +978,7 @@ pub const CronJob = struct { fn onPromiseReject(_: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args = callframe.arguments(); var this: *CronJob = args[args.len - 1].asPromisePtr(CronJob); - defer this.deref(); + defer this.releasePendingRef(); const vm = this.global.bunVM(); const err = if (args.len > 0) args[0] else .js_undefined; var promise_value: jsc.JSValue = .js_undefined; diff --git a/src/bun.js/bindings/JSMockFunction.cpp b/src/bun.js/bindings/JSMockFunction.cpp index 12396f6e588a..1c760357186a 100644 --- a/src/bun.js/bindings/JSMockFunction.cpp +++ b/src/bun.js/bindings/JSMockFunction.cpp @@ -1447,8 +1447,6 @@ BUN_DEFINE_HOST_FUNCTION(JSMock__jsNow, (JSC::JSGlobalObject * globalObject, JSC { return JSValue::encode(jsNumber(globalObject->jsDateNow())); } -extern "C" void Bun__FakeTimers__onSetSystemTime(double jsEpochMs); - BUN_DEFINE_HOST_FUNCTION(JSMock__jsSetSystemTime, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callframe)) { JSValue argument0 = callframe->argument(0); @@ -1456,13 +1454,11 @@ BUN_DEFINE_HOST_FUNCTION(JSMock__jsSetSystemTime, (JSC::JSGlobalObject * globalO if (auto* dateInstance = jsDynamicCast<DateInstance*>(argument0)) { if (std::isnormal(dateInstance->internalNumber())) { globalObject->overridenDateNow = dateInstance->internalNumber(); - Bun__FakeTimers__onSetSystemTime(dateInstance->internalNumber()); } return JSValue::encode(callframe->thisValue()); } // number > 0 is a valid date otherwise it's invalid and we should reset the time (set to -1) globalObject->overridenDateNow = (argument0.isNumber() && argument0.asNumber() >= 0) ? argument0.asNumber() : -1; - Bun__FakeTimers__onSetSystemTime(globalObject->overridenDateNow); return JSValue::encode(callframe->thisValue()); } diff --git a/src/bun.js/test/timers/FakeTimers.zig b/src/bun.js/test/timers/FakeTimers.zig index 71e96ef10237..4caf05d62488 100644 --- a/src/bun.js/test/timers/FakeTimers.zig +++ b/src/bun.js/test/timers/FakeTimers.zig @@ -18,18 +18,6 @@ pub var current_time: struct { if (value.eql(&min_timespec)) return null; return value; } - /// Mocked epoch milliseconds (what JS Date.now() returns under fake timers). - pub fn dateNowMs(this: *@This()) ?f64 { - const ts = this.getTimespecNow() orelse return null; - return this.date_now_offset + @as(f64, @floatFromInt(ts.ms())); - } - /// Called from JSMock__jsSetSystemTime so that a subsequent - /// advanceTimersByTime() continues from the value setSystemTime set - /// instead of reverting to the offset captured at useFakeTimers(). - pub fn onSetSystemTime(this: *@This(), js_epoch_ms: f64) void { - const ts = this.getTimespecNow() orelse return; - this.date_now_offset = js_epoch_ms - @as(f64, @floatFromInt(ts.ms())); - } pub fn set(this: *@This(), globalObject: *jsc.JSGlobalObject, v: struct { offset: *const bun.timespec, js: ?f64 = null, @@ -378,12 +366,6 @@ pub fn putTimersFns(globalObject: *jsc.JSGlobalObject, jest: jsc.JSValue, vi: js } } -pub export fn Bun__FakeTimers__onSetSystemTime(js_epoch_ms: f64) void { - // -1 = setSystemTime() reset; re-anchor date_now_offset to real time so - // a later advanceTimersByTime doesn't resurrect the previously-set value. - current_time.onSetSystemTime(if (js_epoch_ms < 0) @floatFromInt(std.time.milliTimestamp()) else js_epoch_ms); -} - const bindgen_generated = @import("bindgen_generated"); const std = @import("std"); diff --git a/src/bun.js/web_worker.zig b/src/bun.js/web_worker.zig index d9d0a33367e3..ce848f5e8d17 100644 --- a/src/bun.js/web_worker.zig +++ b/src/bun.js/web_worker.zig @@ -603,7 +603,7 @@ pub fn exitAndDeinit(this: *WebWorker) noreturn { loop = vm.uwsLoop(); this.vm = null; vm.is_shutting_down = true; - jsc.API.cron.CronJob.clearAllForVM(vm); + jsc.API.cron.CronJob.clearAllForVM(vm, .teardown); vm.onExit(); exit_code = vm.exit_handler.exit_code; globalObject = vm.global; diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index 677c49856738..cde4f3597eff 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -121,18 +121,15 @@ describe("Bun.cron (in-process)", () => { expect(exitCode).toBe(0); }); - test("respects jest fake timers via mocked Date.now()", () => { + test("ignores jest fake timers (calendar-anchored to real time)", () => { jest.useFakeTimers(); try { - jest.setSystemTime(new Date("2025-01-01T23:59:30Z")); let fires = 0; - using job = Bun.cron("0 0 * * *", () => void fires++); - jest.advanceTimersByTime(29_000); + using job = Bun.cron("* * * * *", () => void fires++); + jest.runAllTimers(); + jest.advanceTimersByTime(120_000); + jest.runAllTimers(); expect(fires).toBe(0); - jest.advanceTimersByTime(2_000); - expect(fires).toBe(1); - jest.advanceTimersByTime(24 * 60 * 60_000); - expect(fires).toBe(2); } finally { jest.useRealTimers(); } @@ -148,55 +145,38 @@ describe("Bun.cron (in-process)", () => { }); }); -describe("Bun.cron (in-process) — firing (fake timers)", () => { - test("callback fires at minute boundary, this === job", () => { - jest.useFakeTimers(); - try { - jest.setSystemTime(new Date("2025-01-01T00:00:30Z")); - let fired = 0; - let thisInCallback: unknown; - using job = Bun.cron("* * * * *", function () { - fired++; - thisInCallback = this; - }); - jest.advanceTimersByTime(30_000); - expect(fired).toBe(1); - expect(thisInCallback).toBe(job); - jest.advanceTimersByTime(60_000); - expect(fired).toBe(2); - } finally { - jest.useRealTimers(); - } - }); +describe.concurrent("Bun.cron (in-process) — firing", () => { + test("callback fires at minute boundary, this === job", async () => { + let fired = 0; + let thisInCallback: unknown; + const { promise, resolve } = Promise.withResolvers<void>(); - test("async callback delays next scheduling (no overlap)", async () => { - jest.useFakeTimers(); - try { - jest.setSystemTime(new Date("2025-01-01T00:00:59Z")); - let starts = 0; - const handler = Promise.withResolvers<void>(); - using job = Bun.cron("* * * * *", async () => { - starts++; - await handler.promise; - }); - jest.advanceTimersByTime(1_000); - expect(starts).toBe(1); - // Handler still pending — advancing past 5 more boundaries must not stack fires. - jest.advanceTimersByTime(5 * 60_000); - expect(starts).toBe(1); - handler.resolve(); - // Drain the .then() chain so onPromiseResolve runs and reschedules. - for (let i = 0; i < 3; i++) await Promise.resolve(); - // Next fire scheduled from current fake time; one more minute triggers it. - jest.advanceTimersByTime(60_000); - expect(starts).toBe(2); - } finally { - jest.useRealTimers(); - } - }); -}); + using job = Bun.cron("* * * * *", function () { + fired++; + thisInCallback = this; + resolve(); + }); + + await promise; + expect(fired).toBe(1); + expect(thisInCallback).toBe(job); + }, 70_000); + + test("async callback delays next scheduling", async () => { + const handler = Promise.withResolvers<void>(); + const fire = Promise.withResolvers<void>(); + + using job = Bun.cron("* * * * *", async () => { + fire.resolve(); + await handler.promise; + }); + + await fire.promise; + job.stop(); + handler.resolve(); + await Bun.sleep(10); + }, 70_000); -describe.concurrent("Bun.cron (in-process) — firing (subprocess)", () => { test("sync throw in callback emits uncaughtException", async () => { // Matches setTimeout: sync throw → uncaughtException. Process exits 1 without a handler. await using proc = Bun.spawn({ diff --git a/test/js/bun/test/fake-timers/fake-timers.test.ts b/test/js/bun/test/fake-timers/fake-timers.test.ts index f1d740f565c3..40ae5b1daae3 100644 --- a/test/js/bun/test/fake-timers/fake-timers.test.ts +++ b/test/js/bun/test/fake-timers/fake-timers.test.ts @@ -1,4 +1,3 @@ -import { setSystemTime } from "bun:test"; import { afterEach, describe, expect, test, vi } from "vitest"; afterEach(() => vi.useRealTimers()); @@ -214,23 +213,6 @@ describe("isFakeTimers", () => { }); }); describe("Date.now() mocking", () => { - test("setSystemTime composes with advanceTimersByTime", () => { - vi.useFakeTimers(); - setSystemTime(new Date("2020-06-15T12:00:00Z")); - expect(Date.now()).toBe(new Date("2020-06-15T12:00:00Z").getTime()); - vi.advanceTimersByTime(5000); - expect(Date.now()).toBe(new Date("2020-06-15T12:00:05Z").getTime()); - }); - - test("setSystemTime() reset then advanceTimersByTime tracks real time", () => { - vi.useFakeTimers(); - setSystemTime(new Date("2020-06-15T12:00:00Z")); - setSystemTime(); // reset - const realYear = new Date().getFullYear(); - vi.advanceTimersByTime(1000); - expect(new Date().getFullYear()).toBe(realYear); - }); - test("Date.now() before and after vi.useFakeTimers() should be roughly equal", () => { const beforeFake = Date.now(); vi.useFakeTimers(); From 188aeddf634edb43ea9346f4ac2f166b54102824 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 21:10:08 -0700 Subject: [PATCH 25/58] Defer this_value downgrade until pending promise settles Keeps the JS wrapper strong while a callback promise is in flight so onPromiseReject can read pendingPromise from the WriteBarrier slot and pass the real Promise to unhandledRejection instead of undefined. --- src/bun.js/api/cron.zig | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index a32d8565d46a..f2655b78dd20 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -830,12 +830,22 @@ pub const CronJob = struct { this_value: jsc.JSRef = jsc.JSRef.empty(), stopped: bool = false, /// True while a ref() is held across an in-flight callback promise. - /// Released exactly once by either onPromiseResolve/Reject or stopInternal. + /// Released exactly once by either onPromiseResolve/Reject or + /// clearAllForVM(.teardown). pending_ref: bool = false, + /// Defer downgrading the JS wrapper to weak until any in-flight promise + /// has settled, so onPromiseReject can still read pendingPromise from + /// the wrapper and pass the real Promise to unhandledRejection. + fn maybeDowngrade(this: *CronJob) void { + if (this.stopped and !this.pending_ref and this.this_value != .finalized) + this.this_value.downgrade(); + } + fn releasePendingRef(this: *CronJob) void { if (this.pending_ref) { this.pending_ref = false; + this.maybeDowngrade(); this.deref(); } } @@ -846,8 +856,7 @@ pub const CronJob = struct { if (this.event_loop_timer.state == .ACTIVE) vm.timer.remove(&this.event_loop_timer); this.poll_ref.unref(vm); - if (this.this_value != .finalized) - this.this_value.downgrade(); + this.maybeDowngrade(); } fn selfStop(this: *CronJob, vm: *jsc.VirtualMachine) void { From fcdd58099122fb26487df347a2bb8ca7cc07f626 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Wed, 1 Apr 2026 21:13:06 -0700 Subject: [PATCH 26/58] Test: drop reference + GC before reject to verify wrapper stays strong --- test/js/bun/cron/in-process-cron.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index cde4f3597eff..d55436632a34 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -234,8 +234,11 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { console.log("caught=" + e.message + ":" + (p instanceof Promise)); process.exit(0); }); - const job = Bun.cron("* * * * *", async () => { + let job = Bun.cron("* * * * *", async () => { job.stop(); + job = null; + Bun.gc(true); + Bun.gc(true); await Bun.sleep(10); throw new Error("after-stop"); }); From de04dc81e0d389554acf0ced932fcfffbd098567 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 08:17:14 -0700 Subject: [PATCH 27/58] Defer stop() cleanup when called during cb.call() When stop() runs synchronously inside an async callback before the first await, it now only sets stopped=true (in_fire guard) and lets onTimerFire finish the cleanup after the result is known. This keeps the wrapper strong and the job in cron_jobs until either the .pending branch takes pending_ref or the non-pending path runs finishDeferredStop, so: - onPromiseReject can always read pendingPromise (real Promise to unhandledRejection, never undefined) - clearAllForVM(.teardown) can find the job to release pending_ref stopInternal is now idempotent (every step checks its own state). --- src/bun.js/api/cron.zig | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index f2655b78dd20..693e958c8b99 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -833,6 +833,8 @@ pub const CronJob = struct { /// Released exactly once by either onPromiseResolve/Reject or /// clearAllForVM(.teardown). pending_ref: bool = false, + /// True between onTimerFire's cb.call() and processing of its result. + in_fire: bool = false, /// Defer downgrading the JS wrapper to weak until any in-flight promise /// has settled, so onPromiseReject can still read pendingPromise from @@ -850,8 +852,8 @@ pub const CronJob = struct { } } + /// Idempotent — every step checks its own state. fn stopInternal(this: *CronJob, vm: *jsc.VirtualMachine) void { - if (this.stopped) return; this.stopped = true; if (this.event_loop_timer.state == .ACTIVE) vm.timer.remove(&this.event_loop_timer); @@ -859,8 +861,25 @@ pub const CronJob = struct { this.maybeDowngrade(); } + /// Runs the cleanup that selfStop deferred while in_fire was true. + fn finishDeferredStop(this: *CronJob, vm: *jsc.VirtualMachine) void { + this.stopInternal(vm); + this.removeFromList(vm); + } + fn selfStop(this: *CronJob, vm: *jsc.VirtualMachine) void { + // If stop() runs during cb.call() (before .pending is processed), defer + // cleanup so the .pending branch can take pending_ref + keep this_value + // strong. onTimerFire calls finishSelfStop() after the result is known. + if (this.in_fire) { + this.stopped = true; + return; + } this.stopInternal(vm); + this.removeFromList(vm); + } + + fn removeFromList(this: *CronJob, vm: *jsc.VirtualMachine) void { if (vm.rare_data) |rare| { if (std.mem.indexOfScalar(*CronJob, rare.cron_jobs.items, this)) |i| { _ = rare.cron_jobs.swapRemove(i); @@ -940,12 +959,15 @@ pub const CronJob = struct { vm.eventLoop().enter(); defer vm.eventLoop().exit(); + this.in_fire = true; const result = cb.call(this.global, js_this, &.{}) catch { + this.in_fire = false; if (this.global.tryTakeException()) |err| _ = vm.uncaughtException(vm.global, err, false); - this.scheduleNext(vm); + if (this.stopped) this.finishDeferredStop(vm) else this.scheduleNext(vm); return; }; + this.in_fire = false; if (result.asAnyPromise()) |promise| { switch (promise.status()) { @@ -956,7 +978,7 @@ pub const CronJob = struct { result.then(this.global, this, onPromiseResolve, onPromiseReject) catch { js.pendingPromiseSetCached(js_this, this.global, .js_undefined); this.releasePendingRef(); - this.scheduleNext(vm); + if (this.stopped) this.finishDeferredStop(vm) else this.scheduleNext(vm); }; return; }, @@ -968,7 +990,7 @@ pub const CronJob = struct { } } - this.scheduleNext(vm); + if (this.stopped) this.finishDeferredStop(vm) else this.scheduleNext(vm); } pub export const Bun__CronJob__onPromiseResolve = jsc.toJSHostFn(onPromiseResolve); @@ -978,9 +1000,10 @@ pub const CronJob = struct { const args = callframe.arguments(); var this: *CronJob = args[args.len - 1].asPromisePtr(CronJob); defer this.releasePendingRef(); + const vm = this.global.bunVM(); if (this.this_value.tryGet()) |js_this| js.pendingPromiseSetCached(js_this, this.global, .js_undefined); - this.scheduleNext(this.global.bunVM()); + if (this.stopped) this.finishDeferredStop(vm) else this.scheduleNext(vm); return .js_undefined; } @@ -996,7 +1019,7 @@ pub const CronJob = struct { js.pendingPromiseSetCached(js_this, this.global, .js_undefined); } vm.unhandledRejection(vm.global, err, promise_value); - this.scheduleNext(vm); + if (this.stopped) this.finishDeferredStop(vm) else this.scheduleNext(vm); return .js_undefined; } From d19ce6743ef3d65e0bb59bbdad42daeed193772e Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 08:33:09 -0700 Subject: [PATCH 28/58] Unref poll_ref immediately in deferred-stop path stop() before the first await must release the loop ref right away (matching clearInterval), even though downgrade and list-removal are deferred until after cb.call() returns. --- src/bun.js/api/cron.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 693e958c8b99..9e87e29b11da 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -873,6 +873,7 @@ pub const CronJob = struct { // strong. onTimerFire calls finishSelfStop() after the result is known. if (this.in_fire) { this.stopped = true; + this.poll_ref.unref(vm); return; } this.stopInternal(vm); From 164187520278e63b5533f7481cfa0833bb346928 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 08:49:24 -0700 Subject: [PATCH 29/58] cron: interpret schedules in local time instead of UTC MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CronExpression.next() now uses JSC's local-time DateCache conversions so Bun.cron.parse() and the in-process Bun.cron(schedule, handler) match the OS-level overload — crontab/launchd/schtasks all read schedules in local time. DST gaps round forward and duplicated hours fire once (first occurrence), inherited from vm.dateCache. Adds Bun__msToGregorianDateTime (LocalTime) binding alongside the existing UTC variant. --- docs/runtime/cron.mdx | 32 +++++--- packages/bun-types/bun.d.ts | 15 ++-- src/bun.js/api/cron_parser.zig | 15 ++-- src/bun.js/bindings/JSGlobalObject.zig | 7 ++ src/bun.js/bindings/bindings.cpp | 15 ++++ test/js/bun/cron/cron-local-time.test.ts | 95 ++++++++++++++++++++++++ test/js/bun/cron/cron.test.ts | 9 ++- 7 files changed, 162 insertions(+), 26 deletions(-) create mode 100644 test/js/bun/cron/cron-local-time.test.ts diff --git a/docs/runtime/cron.mdx b/docs/runtime/cron.mdx index 50dbcf1541b1..6b3cf0d5f28f 100644 --- a/docs/runtime/cron.mdx +++ b/docs/runtime/cron.mdx @@ -18,9 +18,8 @@ Bun.cron("0 * * * *", async () => { **Parse a cron expression to find the next matching time:** ```ts -// Next weekday at 9:30 AM UTC +// Next weekday at 9:30 AM local time const next = Bun.cron.parse("30 9 * * MON-FRI"); -console.log(next); // => 2025-01-20T09:30:00.000Z ``` **Register an OS-level cron job that runs a script on a schedule:** @@ -33,7 +32,7 @@ await Bun.cron("./worker.ts", "30 2 * * MON", "weekly-report"); ## `Bun.cron.parse()` -Parse a cron expression and return the next matching UTC `Date`. +Parse a cron expression and return the next matching `Date` in the system's local time zone. ```ts const next = Bun.cron.parse("*/15 * * * *"); @@ -49,20 +48,18 @@ console.log(next); // => next quarter-hour boundary ### Returns -`Date | null` — the next matching UTC time, or `null` if no match exists within ~4 years (e.g. February 30th). +`Date | null` — the next matching time, or `null` if no match exists within ~4 years (e.g. February 30th). ### Chaining calls Call `parse()` repeatedly to get a sequence of upcoming times: ```ts -const from = Date.UTC(2025, 0, 15, 10, 0, 0); - -const first = Bun.cron.parse("0 * * * *", from); -console.log(first); // => 2025-01-15T11:00:00.000Z - -const second = Bun.cron.parse("0 * * * *", first); -console.log(second); // => 2025-01-15T12:00:00.000Z +let cursor: Date | number = Date.now(); +for (let i = 0; i < 3; i++) { + cursor = Bun.cron.parse("0 * * * *", cursor)!; + console.log(cursor.toLocaleString()); // next three top-of-hour boundaries +} ``` --- @@ -116,9 +113,20 @@ Both `0` and `7` mean Sunday in the weekday field. ```ts const next = Bun.cron.parse("@daily"); -console.log(next); // => next midnight UTC +console.log(next); // => next local midnight ``` +### Time zone + +Schedules are interpreted in the system's **local time zone** — the same way crontab, launchd, and Windows Task Scheduler read them. The OS-level form and the in-process callback form fire at the same wall-clock time. + +To use UTC, set `TZ=UTC` in the environment. + +DST transitions follow the same rules as `new Date(year, month, day, hour, minute)`: + +- **Spring-forward** — schedules in the missing hour fire at the next valid local minute. +- **Fall-back** — schedules in the duplicated hour fire once, at the first occurrence. + ### Day-of-month and day-of-week interaction When **both** day-of-month and day-of-week are specified (neither is `*`), the expression matches when **either** condition is true. This follows the [POSIX cron](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html) standard. diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index 5e570f6f6413..c6ab95801e98 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7592,7 +7592,9 @@ declare module "bun" { */ remove(title: string): Promise<void>; /** - * Parse a cron expression and return the next matching UTC Date. + * Parse a cron expression and return the next matching `Date` in the + * system's local time zone — the same way crontab, launchd, and Windows + * Task Scheduler interpret schedules. Set `TZ=UTC` to use UTC. * * Supports the same syntax as {@link Bun.cron} — 5-field expressions, named * days/months, and predefined nicknames like `@daily`. @@ -7601,23 +7603,24 @@ declare module "bun" { * matching uses OR logic per [POSIX cron](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html): * a date matches if **either** field matches. * + * DST: schedules in the spring-forward gap fire at the next valid local + * minute; schedules in the fall-back duplicated hour fire once (first + * occurrence). + * * @param expression - A cron expression or nickname (e.g. `"0,15,30,45 * * * *"`, `"0 9 * * MON-FRI"`, `"@hourly"`) * @param relativeDate - Starting point for the search (defaults to `Date.now()`). Accepts a `Date` or milliseconds since epoch. - * @returns The next `Date` matching the expression (UTC), or `null` if no match exists within ~4 years (e.g. `"0 0 30 2 *"` — Feb 30 never occurs) + * @returns The next `Date` matching the expression in local time, or `null` if no match exists within ~4 years (e.g. `"0 0 30 2 *"` — Feb 30 never occurs) * @throws If the expression is invalid or `relativeDate` is `NaN`/`Infinity` * * @example * ```ts - * // Next weekday at 09:30 UTC + * // Next weekday at 09:30 local time * const next = Bun.cron.parse("30 9 * * MON-FRI"); * * // Chain calls to get a sequence * const from = new Date(); * const first = Bun.cron.parse("@hourly", from); * const second = first ? Bun.cron.parse("@hourly", first) : null; - * - * // With a specific starting point - * const nextJan1 = Bun.cron.parse("0 0 1 JAN *", Date.UTC(2025, 0, 1)); * ``` */ parse(expression: CronWithAutocomplete, relativeDate?: Date | number): Date | null; diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index 05c764d6b049..c250a7ef19ae 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -83,10 +83,11 @@ pub const CronExpression = struct { return stream.getWritten(); } - /// Compute the next UTC time (in ms since epoch) that matches this expression, - /// starting from `from_ms`. Returns null if no match found within ~4 years. + /// Compute the next time (in ms since epoch) that matches this expression + /// in the system's local time zone, starting from `from_ms`. Returns null + /// if no match found within ~4 years. pub fn next(self: CronExpression, globalObject: *jsc.JSGlobalObject, from_ms: f64) bun.JSError!?f64 { - var dt = globalObject.msToGregorianDateTimeUTC(from_ms); + var dt = globalObject.msToGregorianDateTime(from_ms); // Advance by 1 minute, zero out seconds dt.minute += 1; @@ -104,10 +105,10 @@ pub const CronExpression = struct { var iterations: u32 = 0; const max_iterations: u32 = 1500 * 24 * 60; while (iterations < max_iterations) : (iterations += 1) { - // Normalize via round-trip to handle overflows and compute weekday + // Normalize via round-trip to handle overflows, DST gaps, and compute weekday { - const ms = try globalObject.gregorianDateTimeToMSUTC(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0); - dt = globalObject.msToGregorianDateTimeUTC(ms); + const ms = try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0); + dt = globalObject.msToGregorianDateTime(ms); } // Check month @@ -147,7 +148,7 @@ pub const CronExpression = struct { } // All fields match - return try globalObject.gregorianDateTimeToMSUTC(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0); + return try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0); } return null; diff --git a/src/bun.js/bindings/JSGlobalObject.zig b/src/bun.js/bindings/JSGlobalObject.zig index e410a266eba8..b32a73f53e0c 100644 --- a/src/bun.js/bindings/JSGlobalObject.zig +++ b/src/bun.js/bindings/JSGlobalObject.zig @@ -49,6 +49,13 @@ pub const JSGlobalObject = opaque { return dt; } + pub fn msToGregorianDateTime(this: *jsc.JSGlobalObject, ms: f64) GregorianDateTime { + jsc.markBinding(@src()); + var dt: GregorianDateTime = undefined; + bun.cpp.Bun__msToGregorianDateTime(this, ms, &dt.year, &dt.month, &dt.day, &dt.hour, &dt.minute, &dt.second, &dt.weekday); + return dt; + } + pub fn throwTODO(this: *JSGlobalObject, msg: []const u8) bun.JSError { const err = this.createErrorInstance("{s}", .{msg}); if (err == .zero) { diff --git a/src/bun.js/bindings/bindings.cpp b/src/bun.js/bindings/bindings.cpp index b39e11521e00..b7c2ef933d66 100644 --- a/src/bun.js/bindings/bindings.cpp +++ b/src/bun.js/bindings/bindings.cpp @@ -5800,6 +5800,21 @@ extern "C" [[ZIG_EXPORT(nothrow)]] void Bun__msToGregorianDateTimeUTC(JSC::JSGlo *weekday = dt.weekDay(); } +extern "C" [[ZIG_EXPORT(nothrow)]] void Bun__msToGregorianDateTime(JSC::JSGlobalObject* globalObject, double ms, + int* year, int* month, int* day, int* hour, int* minute, int* second, int* weekday) +{ + auto& vm = JSC::getVM(globalObject); + WTF::GregorianDateTime dt; + vm.dateCache.msToGregorianDateTime(ms, WTF::TimeType::LocalTime, dt); + *year = dt.year(); + *month = dt.month() + 1; + *day = dt.monthDay(); + *hour = dt.hour(); + *minute = dt.minute(); + *second = dt.second(); + *weekday = dt.weekDay(); +} + extern "C" EncodedJSValue JSC__JSValue__dateInstanceFromNumber(JSC::JSGlobalObject* globalObject, double unixTimestamp) { auto& vm = JSC::getVM(globalObject); diff --git a/test/js/bun/cron/cron-local-time.test.ts b/test/js/bun/cron/cron-local-time.test.ts new file mode 100644 index 000000000000..19a15422f545 --- /dev/null +++ b/test/js/bun/cron/cron-local-time.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, test } from "bun:test"; +import { bunEnv, bunExe } from "harness"; + +// Bun.cron.parse() and the in-process Bun.cron(schedule, handler) interpret +// cron expressions in the system's local time zone — matching the OS-level +// overload (crontab/launchd/schtasks all use local time). +// +// Each test spawns a subprocess with a fixed TZ so the assertions are +// independent of the host's zone. + +async function parseInTZ(tz: string, expr: string, fromISO: string): Promise<string> { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + `process.stdout.write(Bun.cron.parse(${JSON.stringify(expr)}, new Date(${JSON.stringify(fromISO)})).toISOString())`, + ], + env: { ...bunEnv, TZ: tz }, + }); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + expect(exitCode).toBe(0); + return stdout; +} + +describe("Bun.cron.parse — local time zone", () => { + test("0 9 * * * in America/Los_Angeles is 9am Pacific (PDT = UTC-7)", async () => { + const next = await parseInTZ("America/Los_Angeles", "0 9 * * *", "2026-06-15T00:00:00Z"); + // 2026-06-15 00:00 UTC = 2026-06-14 17:00 PDT; next 9am PDT = 2026-06-15 09:00 PDT = 16:00 UTC + expect(next).toBe("2026-06-15T16:00:00.000Z"); + }); + + test("0 9 * * * in UTC is 9am UTC", async () => { + const next = await parseInTZ("UTC", "0 9 * * *", "2026-06-15T00:00:00Z"); + expect(next).toBe("2026-06-15T09:00:00.000Z"); + }); + + test("0 9 * * * in Asia/Tokyo is 9am JST (UTC+9, no DST)", async () => { + const next = await parseInTZ("Asia/Tokyo", "0 9 * * *", "2026-06-15T00:00:00Z"); + // 2026-06-15 00:00 UTC = 2026-06-15 09:00 JST → already at 09:00 but parse() returns the + // NEXT occurrence strictly after, so next is 2026-06-16 09:00 JST = 2026-06-16 00:00 UTC + expect(next).toBe("2026-06-16T00:00:00.000Z"); + }); + + test("weekday matching uses local day-of-week (0 12 * * MON across the dateline)", async () => { + // Pacific/Auckland is UTC+12 (NZST in June). 2026-06-15 is a Monday in NZST. + // 12:00 NZST = 00:00 UTC same date. + const next = await parseInTZ("Pacific/Auckland", "0 12 * * MON", "2026-06-14T23:00:00Z"); + // 2026-06-14 23:00 UTC = 2026-06-15 11:00 NZST (Mon); next Mon 12:00 NZST = 2026-06-15 00:00 UTC + expect(next).toBe("2026-06-15T00:00:00.000Z"); + }); +}); + +describe("Bun.cron.parse — DST transitions", () => { + test("spring-forward: schedule in the missing hour rounds forward", async () => { + // US 2025 spring-forward: 2025-03-09 02:00 EST → 03:00 EDT (2:00-2:59 don't exist). + // Schedule "30 2 * * *" on that day should land at the next valid local minute. + const next = await parseInTZ("America/New_York", "30 2 * * *", "2025-03-09T05:00:00Z"); // = 00:00 EST + const date = new Date(next); + // The result must be on or after 03:00 EDT (= 07:00 UTC) — the missing 02:30 is skipped. + expect(date.getTime()).toBeGreaterThanOrEqual(new Date("2025-03-09T07:00:00Z").getTime()); + // ...and no later than the next day's 02:30 EDT (= 06:30 UTC on the 10th). + expect(date.getTime()).toBeLessThanOrEqual(new Date("2025-03-10T06:30:00Z").getTime()); + }); + + test("fall-back: schedule in the duplicated hour fires at the first occurrence", async () => { + // US 2025 fall-back: 2025-11-02 02:00 EDT → 01:00 EST (1:00-1:59 occurs twice). + // Starting from 00:30 EDT (= 04:30 UTC), next "30 1 * * *" is the first 01:30 (EDT) = 05:30 UTC. + const next = await parseInTZ("America/New_York", "30 1 * * *", "2025-11-02T04:30:00Z"); + expect(next).toBe("2025-11-02T05:30:00.000Z"); + }); +}); + +describe("Bun.cron(schedule, handler) — local time zone", () => { + test("registering 0 9 * * * computes the same next-fire as Bun.cron.parse in local time", async () => { + // The in-process scheduler uses the same next() — we verify via parse() since + // waiting for an actual fire would take up to 24 hours. + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + const expr = "0 9 * * *"; + const parsed = Bun.cron.parse(expr).getTime(); + // Register and immediately stop; the deadline was computed from the same next(). + using job = Bun.cron(expr, () => {}); + process.stdout.write(String(parsed > Date.now())); + `, + ], + env: { ...bunEnv, TZ: "America/Los_Angeles" }, + }); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + expect(stdout).toBe("true"); + expect(exitCode).toBe(0); + }); +}); diff --git a/test/js/bun/cron/cron.test.ts b/test/js/bun/cron/cron.test.ts index bf24eab225ea..21216a0176ab 100644 --- a/test/js/bun/cron/cron.test.ts +++ b/test/js/bun/cron/cron.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test } from "bun:test"; +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { bunEnv, bunExe, isLinux, isMacOS, isWindows, tempDir } from "harness"; import { existsSync, readFileSync, unlinkSync, watch, writeFileSync } from "node:fs"; import { basename } from "node:path"; @@ -1405,6 +1405,13 @@ function nextN(expr: string, from: number, n: number): number[] { } describe("Bun.cron.parse", () => { + // parse() now interprets expressions in local time. These tests were written + // with Date.UTC inputs/expectations, so pin to UTC for this block. Local-time + // behavior is covered in cron-local-time.test.ts. + const savedTZ = process.env.TZ; + beforeAll(() => void (process.env.TZ = "UTC")); + afterAll(() => void (savedTZ === undefined ? delete process.env.TZ : (process.env.TZ = savedTZ))); + test("is a function that returns a Date", () => { expect(typeof Bun.cron.parse).toBe("function"); const result = Bun.cron.parse("* * * * *", Date.UTC(2025, 0, 15, 10, 30, 0)); From ca0f099f14f347d52a506b0742c7df7e8f566c3c Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 08:56:27 -0700 Subject: [PATCH 30/58] docs: clarify spring-forward DST skips to next occurrence --- docs/runtime/cron.mdx | 4 ++-- packages/bun-types/bun.d.ts | 6 +++--- test/js/bun/cron/cron-local-time.test.ts | 10 +++------- 3 files changed, 8 insertions(+), 12 deletions(-) diff --git a/docs/runtime/cron.mdx b/docs/runtime/cron.mdx index 6b3cf0d5f28f..d7c82aa9be17 100644 --- a/docs/runtime/cron.mdx +++ b/docs/runtime/cron.mdx @@ -122,9 +122,9 @@ Schedules are interpreted in the system's **local time zone** — the same way c To use UTC, set `TZ=UTC` in the environment. -DST transitions follow the same rules as `new Date(year, month, day, hour, minute)`: +DST transitions: -- **Spring-forward** — schedules in the missing hour fire at the next valid local minute. +- **Spring-forward** — a schedule that lands in the missing hour is skipped that day; it fires at its next normal occurrence. - **Fall-back** — schedules in the duplicated hour fire once, at the first occurrence. ### Day-of-month and day-of-week interaction diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index c6ab95801e98..2f78dc17fd69 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7603,9 +7603,9 @@ declare module "bun" { * matching uses OR logic per [POSIX cron](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html): * a date matches if **either** field matches. * - * DST: schedules in the spring-forward gap fire at the next valid local - * minute; schedules in the fall-back duplicated hour fire once (first - * occurrence). + * DST: a schedule that lands in the spring-forward gap is skipped that day + * and fires at its next normal occurrence; schedules in the fall-back + * duplicated hour fire once (first occurrence). * * @param expression - A cron expression or nickname (e.g. `"0,15,30,45 * * * *"`, `"0 9 * * MON-FRI"`, `"@hourly"`) * @param relativeDate - Starting point for the search (defaults to `Date.now()`). Accepts a `Date` or milliseconds since epoch. diff --git a/test/js/bun/cron/cron-local-time.test.ts b/test/js/bun/cron/cron-local-time.test.ts index 19a15422f545..5172b6c4ac41 100644 --- a/test/js/bun/cron/cron-local-time.test.ts +++ b/test/js/bun/cron/cron-local-time.test.ts @@ -51,15 +51,11 @@ describe("Bun.cron.parse — local time zone", () => { }); describe("Bun.cron.parse — DST transitions", () => { - test("spring-forward: schedule in the missing hour rounds forward", async () => { + test("spring-forward: schedule in the missing hour skips to the next day", async () => { // US 2025 spring-forward: 2025-03-09 02:00 EST → 03:00 EDT (2:00-2:59 don't exist). - // Schedule "30 2 * * *" on that day should land at the next valid local minute. + // "30 2 * * *" on that day skips to the next normal occurrence: 2025-03-10 02:30 EDT. const next = await parseInTZ("America/New_York", "30 2 * * *", "2025-03-09T05:00:00Z"); // = 00:00 EST - const date = new Date(next); - // The result must be on or after 03:00 EDT (= 07:00 UTC) — the missing 02:30 is skipped. - expect(date.getTime()).toBeGreaterThanOrEqual(new Date("2025-03-09T07:00:00Z").getTime()); - // ...and no later than the next day's 02:30 EDT (= 06:30 UTC on the 10th). - expect(date.getTime()).toBeLessThanOrEqual(new Date("2025-03-10T06:30:00Z").getTime()); + expect(next).toBe("2025-03-10T06:30:00.000Z"); // 02:30 EDT }); test("fall-back: schedule in the duplicated hour fires at the first occurrence", async () => { From c0ae5e8719f0a73b505775f582c5e58d7ad4a9c1 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 08:57:14 -0700 Subject: [PATCH 31/58] Fix stray UTC reference in cron_parser module comment --- src/bun.js/api/cron_parser.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index c250a7ef19ae..82d53b58de6d 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -1,7 +1,7 @@ /// Cron expression parser and next-occurrence calculator. /// /// Parses standard 5-field cron expressions (minute hour day month weekday) -/// into a bitset representation, and computes the next matching UTC time. +/// into a bitset representation, and computes the next matching local time. /// /// Supports: /// - Wildcards: * From 282b60b9df6fab2620d052c9662bc32ee9588e19 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 09:48:28 -0700 Subject: [PATCH 32/58] cron_parser: guard against fall-back returning a time before from_ms During DST fall-back, gregorianDateTimeToMS picks the first occurrence of an ambiguous local time. If from_ms is already in the second occurrence, the match could be earlier than from_ms, causing computeNextTimespec to clamp to 1ms and tight-loop. Now next() keeps searching until result > from_ms. Also: fix finishSelfStop -> finishDeferredStop typo in comment. --- src/bun.js/api/cron.zig | 2 +- src/bun.js/api/cron_parser.zig | 10 +++++++++- test/js/bun/cron/cron-local-time.test.ts | 7 +++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 9e87e29b11da..cc6c9db7cf16 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -870,7 +870,7 @@ pub const CronJob = struct { fn selfStop(this: *CronJob, vm: *jsc.VirtualMachine) void { // If stop() runs during cb.call() (before .pending is processed), defer // cleanup so the .pending branch can take pending_ref + keep this_value - // strong. onTimerFire calls finishSelfStop() after the result is known. + // strong. onTimerFire calls finishDeferredStop() after the result is known. if (this.in_fire) { this.stopped = true; this.poll_ref.unref(vm); diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index 82d53b58de6d..c4a5d87d9f1d 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -148,7 +148,15 @@ pub const CronExpression = struct { } // All fields match - return try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0); + const result = try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0); + // During DST fall-back, gregorianDateTimeToMS picks the first + // occurrence of an ambiguous local time. If from_ms is already past + // it (in the second occurrence), keep searching. + if (result <= from_ms) { + dt.minute += 1; + continue; + } + return result; } return null; diff --git a/test/js/bun/cron/cron-local-time.test.ts b/test/js/bun/cron/cron-local-time.test.ts index 5172b6c4ac41..97bce77beec9 100644 --- a/test/js/bun/cron/cron-local-time.test.ts +++ b/test/js/bun/cron/cron-local-time.test.ts @@ -64,6 +64,13 @@ describe("Bun.cron.parse — DST transitions", () => { const next = await parseInTZ("America/New_York", "30 1 * * *", "2025-11-02T04:30:00Z"); expect(next).toBe("2025-11-02T05:30:00.000Z"); }); + + test("fall-back: starting from the second occurrence does not return a time before from", async () => { + // 06:30 UTC = 01:30 EST (the SECOND 01:30). next() must not return the first 01:30 (05:30 UTC). + const next = await parseInTZ("America/New_York", "30 1 * * *", "2025-11-02T06:30:00Z"); + // Next valid 01:30 is the following day (EST): 2025-11-03 01:30 EST = 06:30 UTC. + expect(next).toBe("2025-11-03T06:30:00.000Z"); + }); }); describe("Bun.cron(schedule, handler) — local time zone", () => { From fb7a836b7e74d6c357b6af5dea74d144b6bef62b Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 10:29:59 -0700 Subject: [PATCH 33/58] Use describe.concurrent for cron-local-time subprocess tests --- test/js/bun/cron/cron-local-time.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/js/bun/cron/cron-local-time.test.ts b/test/js/bun/cron/cron-local-time.test.ts index 97bce77beec9..70d0daf70469 100644 --- a/test/js/bun/cron/cron-local-time.test.ts +++ b/test/js/bun/cron/cron-local-time.test.ts @@ -22,7 +22,7 @@ async function parseInTZ(tz: string, expr: string, fromISO: string): Promise<str return stdout; } -describe("Bun.cron.parse — local time zone", () => { +describe.concurrent("Bun.cron.parse — local time zone", () => { test("0 9 * * * in America/Los_Angeles is 9am Pacific (PDT = UTC-7)", async () => { const next = await parseInTZ("America/Los_Angeles", "0 9 * * *", "2026-06-15T00:00:00Z"); // 2026-06-15 00:00 UTC = 2026-06-14 17:00 PDT; next 9am PDT = 2026-06-15 09:00 PDT = 16:00 UTC @@ -50,7 +50,7 @@ describe("Bun.cron.parse — local time zone", () => { }); }); -describe("Bun.cron.parse — DST transitions", () => { +describe.concurrent("Bun.cron.parse — DST transitions", () => { test("spring-forward: schedule in the missing hour skips to the next day", async () => { // US 2025 spring-forward: 2025-03-09 02:00 EST → 03:00 EDT (2:00-2:59 don't exist). // "30 2 * * *" on that day skips to the next normal occurrence: 2025-03-10 02:30 EDT. @@ -73,7 +73,7 @@ describe("Bun.cron.parse — DST transitions", () => { }); }); -describe("Bun.cron(schedule, handler) — local time zone", () => { +describe.concurrent("Bun.cron(schedule, handler) — local time zone", () => { test("registering 0 9 * * * computes the same next-fire as Bun.cron.parse in local time", async () => { // The in-process scheduler uses the same next() — we verify via parse() since // waiting for an actual fire would take up to 24 hours. From 79f99cbbee1a2978ed8a21d9fa4aa1c8cec4cdd2 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 12:08:10 -0700 Subject: [PATCH 34/58] cron_parser: spring-forward fires same day; selfStop defers when pending_ref - next() checks candidate hour:minute before DST shifts it (matches Vixie/ cron-parser/croner). Explicit carry + noon round-trip for date only; date_dirty guard skips the round-trip when only hour/minute moved. - selfStop defers list removal when pending_ref is set (not just in_fire) so clearAllForVM(.teardown) can find the job and release the ref. - scheduleNext now handles the deferred-stop tail (5 callsites simplified). - Better error for Bun.cron(schedule, non-callable); module doc updated; --hot test pipes stderr and asserts exit code. --- docs/runtime/cron.mdx | 6 ++-- packages/bun-types/bun.d.ts | 6 ++-- src/bun.js/api/cron.zig | 35 ++++++++++++++---------- src/bun.js/api/cron_parser.zig | 30 +++++++++++++++++--- test/js/bun/cron/cron-local-time.test.ts | 7 +++-- test/js/bun/cron/in-process-cron.test.ts | 7 +++-- 6 files changed, 61 insertions(+), 30 deletions(-) diff --git a/docs/runtime/cron.mdx b/docs/runtime/cron.mdx index d7c82aa9be17..191eb94eb6bd 100644 --- a/docs/runtime/cron.mdx +++ b/docs/runtime/cron.mdx @@ -122,10 +122,10 @@ Schedules are interpreted in the system's **local time zone** — the same way c To use UTC, set `TZ=UTC` in the environment. -DST transitions: +DST transitions match Vixie cron and the popular npm parsers (`cron-parser`, `croner`): -- **Spring-forward** — a schedule that lands in the missing hour is skipped that day; it fires at its next normal occurrence. -- **Fall-back** — schedules in the duplicated hour fire once, at the first occurrence. +- **Spring-forward** — a schedule that lands in the missing hour fires that day, shifted forward by the gap (e.g. `30 2 * * *` runs at 3:30 on the spring-forward day). +- **Fall-back** — a schedule in the duplicated hour fires once, at the first occurrence. ### Day-of-month and day-of-week interaction diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index 2f78dc17fd69..dfe4f5a4f424 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7603,9 +7603,9 @@ declare module "bun" { * matching uses OR logic per [POSIX cron](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html): * a date matches if **either** field matches. * - * DST: a schedule that lands in the spring-forward gap is skipped that day - * and fires at its next normal occurrence; schedules in the fall-back - * duplicated hour fire once (first occurrence). + * DST: a schedule that lands in the spring-forward gap fires that day, + * shifted forward by the gap (matching Vixie cron and `cron-parser`); + * schedules in the fall-back duplicated hour fire once (first occurrence). * * @param expression - A cron expression or nickname (e.g. `"0,15,30,45 * * * *"`, `"0 9 * * MON-FRI"`, `"@hourly"`) * @param relativeDate - Starting point for the search (defaults to `Date.now()`). Accepts a `Date` or milliseconds since epoch. diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index cc6c9db7cf16..339992a04827 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -1,10 +1,12 @@ -/// Bun.cron - Register and remove OS-level cron jobs. +/// Bun.cron - in-process and OS-level cron scheduling. /// -/// Bun.cron(path, schedule, title) - register a cron job (returns Promise) -/// Bun.cron.remove(title) - remove a cron job (returns Promise) +/// Bun.cron(schedule, handler) - run a callback on a schedule (returns CronJob) +/// Bun.cron(path, schedule, title) - register an OS-level job (returns Promise) +/// Bun.cron.remove(title) - remove an OS-level job (returns Promise) +/// Bun.cron.parse(expr, from?) - next-occurrence calculator (returns Date | null) /// -/// On Linux, uses crontab. On macOS, uses launchctl + launchd plist. -/// Async, event-loop-integrated implementation using bun.spawn. +/// OS-level uses crontab (Linux), launchctl + launchd plist (macOS), or +/// schtasks (Windows). Async, event-loop-integrated via bun.spawn. /// Shared base for CronRegisterJob and CronRemoveJob. fn CronJobBase(comptime Self: type) type { return struct { @@ -416,6 +418,8 @@ pub const CronRegisterJob = struct { // In-process callback cron: Bun.cron(schedule, handler) if (args[1].isCallable()) return CronJob.register(globalObject, args[0], args[1]); + if (args[0].isString() and args[2].isUndefined()) + return globalObject.throwInvalidArguments("Bun.cron(schedule, handler) expects a function handler as the second argument", .{}); if (!args[0].isString()) return globalObject.throwInvalidArguments("Bun.cron() expects a string path as the first argument", .{}); if (!args[1].isString()) return globalObject.throwInvalidArguments("Bun.cron() expects a string schedule as the second argument", .{}); @@ -868,10 +872,11 @@ pub const CronJob = struct { } fn selfStop(this: *CronJob, vm: *jsc.VirtualMachine) void { - // If stop() runs during cb.call() (before .pending is processed), defer - // cleanup so the .pending branch can take pending_ref + keep this_value - // strong. onTimerFire calls finishDeferredStop() after the result is known. - if (this.in_fire) { + // While the callback is on the stack or its promise is pending, defer + // list removal + downgrade to finishDeferredStop (called from + // scheduleNext after settle) so onPromiseReject can read pendingPromise + // and clearAllForVM(.teardown) can release pending_ref. + if (this.in_fire or this.pending_ref) { this.stopped = true; this.poll_ref.unref(vm); return; @@ -923,7 +928,7 @@ pub const CronJob = struct { } fn scheduleNext(this: *CronJob, vm: *jsc.VirtualMachine) void { - if (this.stopped) return; + if (this.stopped) return this.finishDeferredStop(vm); const next_time = this.computeNextTimespec() orelse { this.selfStop(vm); return; @@ -965,7 +970,7 @@ pub const CronJob = struct { this.in_fire = false; if (this.global.tryTakeException()) |err| _ = vm.uncaughtException(vm.global, err, false); - if (this.stopped) this.finishDeferredStop(vm) else this.scheduleNext(vm); + this.scheduleNext(vm); return; }; this.in_fire = false; @@ -979,7 +984,7 @@ pub const CronJob = struct { result.then(this.global, this, onPromiseResolve, onPromiseReject) catch { js.pendingPromiseSetCached(js_this, this.global, .js_undefined); this.releasePendingRef(); - if (this.stopped) this.finishDeferredStop(vm) else this.scheduleNext(vm); + this.scheduleNext(vm); }; return; }, @@ -991,7 +996,7 @@ pub const CronJob = struct { } } - if (this.stopped) this.finishDeferredStop(vm) else this.scheduleNext(vm); + this.scheduleNext(vm); } pub export const Bun__CronJob__onPromiseResolve = jsc.toJSHostFn(onPromiseResolve); @@ -1004,7 +1009,7 @@ pub const CronJob = struct { const vm = this.global.bunVM(); if (this.this_value.tryGet()) |js_this| js.pendingPromiseSetCached(js_this, this.global, .js_undefined); - if (this.stopped) this.finishDeferredStop(vm) else this.scheduleNext(vm); + this.scheduleNext(vm); return .js_undefined; } @@ -1020,7 +1025,7 @@ pub const CronJob = struct { js.pendingPromiseSetCached(js_this, this.global, .js_undefined); } vm.unhandledRejection(vm.global, err, promise_value); - if (this.stopped) this.finishDeferredStop(vm) else this.scheduleNext(vm); + this.scheduleNext(vm); return .js_undefined; } diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index c4a5d87d9f1d..8b9be8bdf757 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -102,13 +102,33 @@ pub const CronExpression = struct { dt.second = 0; // Loop up to ~4 years to prevent infinite iteration + var date_dirty = true; var iterations: u32 = 0; const max_iterations: u32 = 1500 * 24 * 60; while (iterations < max_iterations) : (iterations += 1) { - // Normalize via round-trip to handle overflows, DST gaps, and compute weekday - { - const ms = try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0); - dt = globalObject.msToGregorianDateTime(ms); + // Carry hour/minute overflow explicitly so the candidate hour:minute + // is checked against the bitfields *before* DST shifts it (Vixie/ + // cron-parser semantics: gap times fire shifted forward, same day). + if (dt.minute > 59) { + dt.minute -= 60; + dt.hour += 1; + } + if (dt.hour > 23) { + dt.hour -= 24; + dt.day += 1; + date_dirty = true; + } + // Normalize the date (year/month/day overflow + weekday) via a + // round-trip at noon, where DST transitions don't occur. Skip when + // only hour/minute moved. + if (date_dirty) { + const noon_ms = try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, 12, 0, 0, 0); + const n = globalObject.msToGregorianDateTime(noon_ms); + dt.year = n.year; + dt.month = n.month; + dt.day = n.day; + dt.weekday = n.weekday; + date_dirty = false; } // Check month @@ -117,6 +137,7 @@ pub const CronExpression = struct { dt.day = 1; dt.hour = 0; dt.minute = 0; + date_dirty = true; continue; } @@ -131,6 +152,7 @@ pub const CronExpression = struct { dt.day += 1; dt.hour = 0; dt.minute = 0; + date_dirty = true; continue; } diff --git a/test/js/bun/cron/cron-local-time.test.ts b/test/js/bun/cron/cron-local-time.test.ts index 70d0daf70469..c5d66854ea1c 100644 --- a/test/js/bun/cron/cron-local-time.test.ts +++ b/test/js/bun/cron/cron-local-time.test.ts @@ -51,11 +51,12 @@ describe.concurrent("Bun.cron.parse — local time zone", () => { }); describe.concurrent("Bun.cron.parse — DST transitions", () => { - test("spring-forward: schedule in the missing hour skips to the next day", async () => { + test("spring-forward: schedule in the missing hour fires shifted forward (same day)", async () => { // US 2025 spring-forward: 2025-03-09 02:00 EST → 03:00 EDT (2:00-2:59 don't exist). - // "30 2 * * *" on that day skips to the next normal occurrence: 2025-03-10 02:30 EDT. + // "30 2 * * *" fires at 03:30 EDT — the gap-shifted instant. Matches Vixie cron, + // cron-parser, and croner. const next = await parseInTZ("America/New_York", "30 2 * * *", "2025-03-09T05:00:00Z"); // = 00:00 EST - expect(next).toBe("2025-03-10T06:30:00.000Z"); // 02:30 EDT + expect(next).toBe("2025-03-09T07:30:00.000Z"); // 03:30 EDT }); test("fall-back: schedule in the duplicated hour fires at the first occurrence", async () => { diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index d55436632a34..ee440ded50c6 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -290,8 +290,9 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { env: bunEnv, cwd: String(dir), stdout: "ignore", - stderr: "ignore", + stderr: "pipe", }); + const stderrP = proc.stderr.text(); while (!(await Bun.file(path("v1.evaluated")).exists())) await Bun.sleep(10); @@ -310,8 +311,10 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { ); while (!(await Bun.file(path("v2.evaluated")).exists())) await Bun.sleep(10); - await proc.exited; + const [exitCode, stderr] = await Promise.all([proc.exited, stderrP]); + if (exitCode !== 0) console.error(stderr); + expect(exitCode).toBe(0); expect(await Bun.file(path("result")).text()).toBe("ok"); expect(await Bun.file(path("ghost.fired")).exists()).toBe(false); }, 130_000); From 397186b2687d6882308d0d2e76afc88f6b97be0e Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 12:09:04 -0700 Subject: [PATCH 35/58] Reword noon round-trip comment: midday DST shifts stay same calendar day --- src/bun.js/api/cron_parser.zig | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index 8b9be8bdf757..0098b13923e0 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -119,8 +119,9 @@ pub const CronExpression = struct { date_dirty = true; } // Normalize the date (year/month/day overflow + weekday) via a - // round-trip at noon, where DST transitions don't occur. Skip when - // only hour/minute moved. + // round-trip at noon. Any DST shift at midday stays within the same + // calendar day, so the date and weekday are still correct. Skip + // when only hour/minute moved. if (date_dirty) { const noon_ms = try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, 12, 0, 0, 0); const n = globalObject.msToGregorianDateTime(noon_ms); From aac68164dd43b788c04201943fd431b7b268f875 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 13:15:01 -0700 Subject: [PATCH 36/58] scheduleNext: use finishDeferredStop on natural-expiry; fix month/weekday name JSDoc selfStop defers when pending_ref is set, so calling it from scheduleNext's natural-expiry branch (inside onPromiseResolve before the defer runs) would never remove from list. finishDeferredStop does the full cleanup directly. --- packages/bun-types/bun.d.ts | 4 ++-- src/bun.js/api/cron.zig | 6 ++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index dfe4f5a4f424..eb590105451c 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7449,7 +7449,7 @@ declare module "bun" { * | Day of week | `0-7` or `SUN`-`SAT` | `*` `,` `-` `/` | * * - `0` and `7` both mean Sunday. - * - Month and weekday names are case-insensitive 3-letter abbreviations. + * - Month and weekday names are case-insensitive (`MON`, `Monday`, `jan`, `January` all work). * - Nicknames: `@yearly`, `@annually`, `@monthly`, `@weekly`, `@daily`, `@midnight`, `@hourly`. * - When both day-of-month and day-of-week are restricted (neither is `*`), the job * fires when **either** matches — [POSIX cron](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html) OR semantics. @@ -7535,7 +7535,7 @@ declare module "bun" { * | Day of week | `0-7` or `SUN`-`SAT` | `*` `,` `-` `/` | * * - `0` and `7` both mean Sunday. - * - Month and weekday names are case-insensitive 3-letter abbreviations. + * - Month and weekday names are case-insensitive (`MON`, `Monday`, `jan`, `January` all work). * - Nicknames: `@yearly`, `@annually`, `@monthly`, `@weekly`, `@daily`, `@midnight`, `@hourly`. * - When both day-of-month and day-of-week are restricted (neither is `*`), the job * fires when **either** matches — [POSIX cron](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html) OR semantics. diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 339992a04827..0e9203714e19 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -929,10 +929,8 @@ pub const CronJob = struct { fn scheduleNext(this: *CronJob, vm: *jsc.VirtualMachine) void { if (this.stopped) return this.finishDeferredStop(vm); - const next_time = this.computeNextTimespec() orelse { - this.selfStop(vm); - return; - }; + const next_time = this.computeNextTimespec() orelse + return this.finishDeferredStop(vm); vm.timer.update(&this.event_loop_timer, &next_time); } From e651c7805da44fa10652016d9a3757701dd60b0f Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 13:30:20 -0700 Subject: [PATCH 37/58] cron: relax handler return type to unknown The JSDoc example `() => fetch(url)` returns Promise<Response>, which TS rejected against MaybePromise<void>. Match node-cron/croner which accept any return value (it's ignored except for promise settling). --- packages/bun-types/bun.d.ts | 8 ++++---- test/integration/bun-types/fixture/cron.ts | 4 ++++ 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index eb590105451c..45eab4ad549a 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7492,7 +7492,7 @@ declare module "bun" { * @see {@link CronJob} for the returned handle. * @see {@link Bun.cron.parse} to preview the next fire time. */ - (schedule: CronWithAutocomplete, handler: (this: CronJob) => MaybePromise<void>): CronJob; + (schedule: CronWithAutocomplete, handler: (this: CronJob) => unknown): CronJob; /** * Register an **OS-level** cron job that runs a JavaScript/TypeScript module on a schedule. * @@ -7603,9 +7603,9 @@ declare module "bun" { * matching uses OR logic per [POSIX cron](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html): * a date matches if **either** field matches. * - * DST: a schedule that lands in the spring-forward gap fires that day, - * shifted forward by the gap (matching Vixie cron and `cron-parser`); - * schedules in the fall-back duplicated hour fire once (first occurrence). + * DST: schedules follow ECMAScript `Date` semantics (matching `croner`) — + * spring-forward times shift forward by the gap; fall-back times fire once + * at the first occurrence. * * @param expression - A cron expression or nickname (e.g. `"0,15,30,45 * * * *"`, `"0 9 * * MON-FRI"`, `"@hourly"`) * @param relativeDate - Starting point for the search (defaults to `Date.now()`). Accepts a `Date` or milliseconds since epoch. diff --git a/test/integration/bun-types/fixture/cron.ts b/test/integration/bun-types/fixture/cron.ts index 2cfbb68da54e..9c57805e05ac 100644 --- a/test/integration/bun-types/fixture/cron.ts +++ b/test/integration/bun-types/fixture/cron.ts @@ -44,6 +44,10 @@ expectType(Bun.cron("./worker.ts", "@daily", "daily")).is<Promise<void>>(); expectType(Bun.cron("* * * * *", () => {})).is<Bun.CronJob>(); expectType(Bun.cron("@hourly", async () => {})).is<Bun.CronJob>(); +expectType(Bun.cron("*/30 * * * *", () => fetch("http://x"))).is<Bun.CronJob>(); +Bun.cron("* * * * *", function () { + this.stop(); +}); using job = Bun.cron("0 * * * *", () => {}); expectType(job.cron).is<string>(); expectType(job.stop()).is<Bun.CronJob>(); From 2e7453db5fc1bd23d26f02b7dda3235d8299303b Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 13:31:01 -0700 Subject: [PATCH 38/58] cron: fix Windows OS-level leaks (stderr_reader, envp arena) --- src/bun.js/api/cron.zig | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 0e9203714e19..9ac0f77fb9ce 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -179,6 +179,7 @@ pub const CronRegisterJob = struct { fn deinit(this: *CronRegisterJob) void { this.stdout_reader.deinit(); + this.stderr_reader.deinit(); if (this.process) |proc| { proc.detach(); proc.deref(); @@ -685,6 +686,7 @@ pub const CronRemoveJob = struct { fn deinit(this: *CronRemoveJob) void { this.stdout_reader.deinit(); + this.stderr_reader.deinit(); if (this.process) |proc| { proc.detach(); proc.deref(); @@ -1166,10 +1168,12 @@ fn spawnCmdGeneric(comptime Self: type, this: *Self, argv: anytype, stdin_opt: b }, }; + var envp_arena = std.heap.ArenaAllocator.init(bun.default_allocator); + defer envp_arena.deinit(); const envp: [*:null]?[*:0]const u8 = if (comptime bun.Environment.isPosix) @ptrCast(@constCast(std.c.environ)) else - @ptrCast((jsc.VirtualMachine.get().transpiler.env.map.createNullDelimitedEnvMap(bun.default_allocator) catch { + @ptrCast((jsc.VirtualMachine.get().transpiler.env.map.createNullDelimitedEnvMap(envp_arena.allocator()) catch { this.setErr("Failed to create environment block", .{}); this.finish(); return; From 91061fadc7ecb2fb37371e31fb6a70b3c1ab283a Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 13:32:23 -0700 Subject: [PATCH 39/58] =?UTF-8?q?cron=5Fparser:=20fold=20weekday=207?= =?UTF-8?q?=E2=86=920=20after=20range=20expansion,=20not=20before?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previously parseValue normalized 7→0 before parseField checked range bounds, so '5-7' became lo=5,hi=0 → InvalidRange, and '0-7' became 0-0 → Sunday only (silent wrong schedule). Now parse weekday with max=7 and fold bit 7 into bit 0 after the bitset is built, matching Vixie/croner/cron-parser. Also makes '7-6' correctly reject as a reversed range instead of silently widening to all days. --- src/bun.js/api/cron_parser.zig | 11 ++++++----- test/js/bun/cron/cron-local-time.test.ts | 23 +++++++++++++++++++++-- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index 0098b13923e0..4c2b81c52076 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -54,7 +54,7 @@ pub const CronExpression = struct { .hours = try parseField(u32, fields[1], 0, 23, .none), .days = try parseField(u32, fields[2], 1, 31, .none), .months = try parseField(u16, fields[3], 1, 12, .month), - .weekdays = try parseField(u8, fields[4], 0, 6, .weekday), + .weekdays = try parseField(u8, fields[4], 0, 7, .weekday), .days_is_wildcard = bun.strings.eql(fields[2], "*"), .weekdays_is_wildcard = bun.strings.eql(fields[4], "*"), }; @@ -107,8 +107,8 @@ pub const CronExpression = struct { const max_iterations: u32 = 1500 * 24 * 60; while (iterations < max_iterations) : (iterations += 1) { // Carry hour/minute overflow explicitly so the candidate hour:minute - // is checked against the bitfields *before* DST shifts it (Vixie/ - // cron-parser semantics: gap times fire shifted forward, same day). + // is checked against the bitfields *before* DST shifts it (croner + // semantics: gap times fire shifted forward, same day). if (dt.minute > 59) { dt.minute -= 60; dt.hour += 1; @@ -281,6 +281,9 @@ fn parseField(comptime T: type, field: []const u8, min: u7, max: u7, kind: NameK if (@as(u8, i) + @as(u8, step) > range_max) break; } } + // Weekday: fold bit 7 (Sunday alias) into bit 0 *after* range expansion so + // 5-7, 0-7, etc. work like Vixie/croner/cron-parser. + if (kind == .weekday) result = (result | (result >> 7)) & 0x7F; return result; } @@ -294,7 +297,6 @@ fn splitRange(base: []const u8) ?[2][]const u8 { } /// Parse a single value (number or name), validating range. -/// For weekday fields, 7 is normalized to 0 (Sunday). fn parseValue(str: []const u8, min: u7, max: u7, kind: NameKind) error{InvalidNumber}!u7 { // Try named value first via ComptimeStringMap case-insensitive lookup switch (kind) { @@ -304,7 +306,6 @@ fn parseValue(str: []const u8, min: u7, max: u7, kind: NameKind) error{InvalidNu } const val = std.fmt.parseInt(u8, str, 10) catch return error.InvalidNumber; - if (kind == .weekday and val == 7) return 0; if (val < min or val > max) return error.InvalidNumber; return @intCast(val); } diff --git a/test/js/bun/cron/cron-local-time.test.ts b/test/js/bun/cron/cron-local-time.test.ts index c5d66854ea1c..fb81b0c9aad1 100644 --- a/test/js/bun/cron/cron-local-time.test.ts +++ b/test/js/bun/cron/cron-local-time.test.ts @@ -50,11 +50,30 @@ describe.concurrent("Bun.cron.parse — local time zone", () => { }); }); +describe.concurrent("Bun.cron.parse — weekday 7 = Sunday in ranges", () => { + // 2026-01-01 is a Thursday. next() is strictly-after, so the first match for an + // every-day schedule is 2026-01-02. + test("1-7 means Mon-Sun (every day)", async () => { + expect(await parseInTZ("UTC", "0 0 * * 1-7", "2026-01-01T00:00:00Z")).toBe("2026-01-02T00:00:00.000Z"); + }); + test("5-7 means Fri-Sun", async () => { + expect(await parseInTZ("UTC", "0 0 * * 5-7", "2026-01-01T00:00:00Z")).toBe("2026-01-02T00:00:00.000Z"); + }); + test("6-7 means Sat-Sun", async () => { + expect(await parseInTZ("UTC", "0 0 * * 6-7", "2026-01-01T00:00:00Z")).toBe("2026-01-03T00:00:00.000Z"); + }); + test("0-7 means every day", async () => { + expect(await parseInTZ("UTC", "0 0 * * 0-7", "2026-01-01T00:00:00Z")).toBe("2026-01-02T00:00:00.000Z"); + }); + test("scalar 7 still means Sunday", async () => { + expect(await parseInTZ("UTC", "0 0 * * 7", "2026-01-01T00:00:00Z")).toBe("2026-01-04T00:00:00.000Z"); + }); +}); + describe.concurrent("Bun.cron.parse — DST transitions", () => { test("spring-forward: schedule in the missing hour fires shifted forward (same day)", async () => { // US 2025 spring-forward: 2025-03-09 02:00 EST → 03:00 EDT (2:00-2:59 don't exist). - // "30 2 * * *" fires at 03:30 EDT — the gap-shifted instant. Matches Vixie cron, - // cron-parser, and croner. + // "30 2 * * *" fires at 03:30 EDT — the gap-shifted instant. Matches croner and cron-parser. const next = await parseInTZ("America/New_York", "30 2 * * *", "2025-03-09T05:00:00Z"); // = 00:00 EST expect(next).toBe("2025-03-09T07:30:00.000Z"); // 03:30 EDT }); From b60a30858985b391cddb9c044a93155dc3c4b011 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 13:37:04 -0700 Subject: [PATCH 40/58] cron: address deep-review findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - year-bail in next() for impossible day/month combos (Feb 30: 848ms→<1ms) - floor next-search at last_next_ms to prevent monotonic/wall skew double-fire - specific parse error messages (TooManyFields, InvalidRange, etc.) - onPromiseReject: drop dead args.len>0 guard - fix stale onTimerFire bracket-ref comment - move clearAllForVM(.teardown) after vm.onExit() (defensive ordering) - debugAssert cron_jobs empty in RareData.deinit - docs: DST transitions match croner only (not Vixie/cron-parser) - tests: add fall-back wildcard, multi-minute spring-forward, Lord Howe, Santiago - tests: add GC-survives, ref-after-stop, worker-teardown; fix no-op async test --- docs/runtime/cron.mdx | 8 ++- src/bun.js/api/cron.zig | 28 +++++--- src/bun.js/api/cron_parser.zig | 33 +++++----- src/bun.js/rare_data.zig | 1 + src/bun.js/web_worker.zig | 2 +- test/js/bun/cron/cron-local-time.test.ts | 48 +++++++------- test/js/bun/cron/in-process-cron.test.ts | 81 +++++++++++++++++++++++- 7 files changed, 147 insertions(+), 54 deletions(-) diff --git a/docs/runtime/cron.mdx b/docs/runtime/cron.mdx index 191eb94eb6bd..89131be591a1 100644 --- a/docs/runtime/cron.mdx +++ b/docs/runtime/cron.mdx @@ -122,10 +122,12 @@ Schedules are interpreted in the system's **local time zone** — the same way c To use UTC, set `TZ=UTC` in the environment. -DST transitions match Vixie cron and the popular npm parsers (`cron-parser`, `croner`): +DST transitions follow ECMAScript `Date` semantics (matching the npm `croner` package): -- **Spring-forward** — a schedule that lands in the missing hour fires that day, shifted forward by the gap (e.g. `30 2 * * *` runs at 3:30 on the spring-forward day). -- **Fall-back** — a schedule in the duplicated hour fires once, at the first occurrence. +- **Spring-forward** — a schedule that lands in the missing hour fires that day, shifted forward by the gap (e.g. `30 2 * * *` runs at 3:30 on the spring-forward day). For multi-minute patterns inside the gap (`*/15 2 * * *`), only the first match fires. +- **Fall-back** — a schedule in the duplicated hour fires once, at the first occurrence. Wildcard schedules (`* * * * *`, `0 * * * *`) also fire once per wall-clock minute, so the repeated hour is skipped in real time. + +This differs from Vixie cron (which runs gap jobs immediately at the end of the gap) and `cron-parser` (which fires through the repeated fall-back hour). ### Day-of-month and day-of-week interaction diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 9ac0f77fb9ce..f4ccf5ebf71d 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -445,8 +445,8 @@ pub const CronRegisterJob = struct { return globalObject.throwInvalidArguments("Cron title must contain only alphanumeric characters, hyphens, and underscores", .{}); // Parse and normalize cron schedule to numeric form for crontab/launchd/schtasks - const parsed = CronExpression.parse(schedule_slice.slice()) catch - return globalObject.throwInvalidArguments("Invalid cron expression. Expected 5 space-separated fields (minute hour day month weekday), each being *, a number, or a range/step pattern", .{}); + const parsed = CronExpression.parse(schedule_slice.slice()) catch |e| + return globalObject.throwInvalidArguments("{s}", .{CronExpression.errorMessage(e)}); var fmt_buf: [512]u8 = undefined; const normalized_schedule = parsed.formatNumeric(&fmt_buf); @@ -835,6 +835,9 @@ pub const CronJob = struct { poll_ref: bun.Async.KeepAlive = .{}, this_value: jsc.JSRef = jsc.JSRef.empty(), stopped: bool = false, + /// Last computed wall-clock fire target (ms epoch); floors the next search + /// so monotonic-vs-wall skew can't recompute the same minute. + last_next_ms: f64 = 0, /// True while a ref() is held across an in-flight callback promise. /// Released exactly once by either onPromiseResolve/Reject or /// clearAllForVM(.teardown). @@ -924,7 +927,12 @@ pub const CronJob = struct { // Cron occurrences are calendar-based (real epoch); the timer heap is // monotonic. Anchor both to real time so fake timers don't half-apply. const now_ms: f64 = @floatFromInt(std.time.milliTimestamp()); - const next_ms = (this.parsed.next(this.global, now_ms) catch return null) orelse return null; + // The monotonic timer can fire fractionally before the wall-clock target + // (clock skew / NTP step); floor next() at the prior target so it can't + // recompute the same minute and double-fire. + const from_ms = @max(now_ms, this.last_next_ms); + const next_ms = (this.parsed.next(this.global, from_ms) catch return null) orelse return null; + this.last_next_ms = next_ms; const delta: i64 = @intFromFloat(@max(1.0, next_ms - now_ms)); return bun.timespec.msFromNow(.force_real_time, delta); } @@ -938,8 +946,8 @@ pub const CronJob = struct { pub fn onTimerFire(this: *CronJob, vm: *jsc.VirtualMachine) void { this.event_loop_timer.state = .FIRED; - // stop() inside the callback downgrades this_value; without this - // ref() a GC could finalize and destroy `this` mid-callback. + // scheduleNext → finishDeferredStop downgrades this_value and derefs the + // list entry; bracket-ref so that path can't drop the last ref mid-function. this.ref(); defer this.deref(); @@ -1018,7 +1026,7 @@ pub const CronJob = struct { var this: *CronJob = args[args.len - 1].asPromisePtr(CronJob); defer this.releasePendingRef(); const vm = this.global.bunVM(); - const err = if (args.len > 0) args[0] else .js_undefined; + const err = args[0]; var promise_value: jsc.JSValue = .js_undefined; if (this.this_value.tryGet()) |js_this| { promise_value = js.pendingPromiseGetCached(js_this) orelse .js_undefined; @@ -1057,8 +1065,8 @@ pub const CronJob = struct { const schedule_slice = schedule_str.toUTF8(bun.default_allocator); defer schedule_slice.deinit(); - const parsed = CronExpression.parse(schedule_slice.slice()) catch - return globalObject.throwInvalidArguments("Invalid cron expression. Expected 5 space-separated fields (minute hour day month weekday), each being *, a number, or a range/step pattern", .{}); + const parsed = CronExpression.parse(schedule_slice.slice()) catch |e| + return globalObject.throwInvalidArguments("{s}", .{CronExpression.errorMessage(e)}); const vm = globalObject.bunVM(); @@ -1112,8 +1120,8 @@ pub fn cronParse(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) b const expr_slice = expr_str.toUTF8(bun.default_allocator); defer expr_slice.deinit(); - const parsed = CronExpression.parse(expr_slice.slice()) catch - return globalObject.throwInvalidArguments("Invalid cron expression. Expected 5 space-separated fields (minute hour day month weekday), each being *, a number, or a range/step pattern", .{}); + const parsed = CronExpression.parse(expr_slice.slice()) catch |e| + return globalObject.throwInvalidArguments("{s}", .{CronExpression.errorMessage(e)}); const from_ms: f64 = if (args[1] != .zero and !args[1].isUndefined() and args[1] != .null) blk: { if (args[1].isNumber()) { diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index 4c2b81c52076..a1096082f460 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -30,6 +30,17 @@ pub const CronExpression = struct { TooFewFields, }; + pub fn errorMessage(e: Error) []const u8 { + return switch (e) { + error.TooFewFields => "Invalid cron expression: expected 5 space-separated fields (minute hour day month weekday)", + error.TooManyFields => "Invalid cron expression: too many fields. Bun.cron uses 5 fields (minute hour day month weekday) — seconds are not supported", + error.InvalidStep => "Invalid cron expression: step value must be a positive integer", + error.InvalidRange => "Invalid cron expression: range must be ascending (use 'a,b' or 'a-max,0-b' for wrap-around)", + error.InvalidNumber => "Invalid cron expression: value out of range for field", + error.InvalidField => "Invalid cron expression: unrecognized field syntax", + }; + } + /// Parse a 5-field cron expression or predefined nickname into a CronExpression. pub fn parse(input: []const u8) Error!CronExpression { const expr = bun.strings.trim(input, " \t"); @@ -85,27 +96,16 @@ pub const CronExpression = struct { /// Compute the next time (in ms since epoch) that matches this expression /// in the system's local time zone, starting from `from_ms`. Returns null - /// if no match found within ~4 years. + /// if no match found within 8 years. pub fn next(self: CronExpression, globalObject: *jsc.JSGlobalObject, from_ms: f64) bun.JSError!?f64 { var dt = globalObject.msToGregorianDateTime(from_ms); + const start_year = dt.year; - // Advance by 1 minute, zero out seconds dt.minute += 1; - if (dt.minute > 59) { - dt.minute = 0; - dt.hour += 1; - if (dt.hour > 23) { - dt.hour = 0; - dt.day += 1; - } - } dt.second = 0; - // Loop up to ~4 years to prevent infinite iteration var date_dirty = true; - var iterations: u32 = 0; - const max_iterations: u32 = 1500 * 24 * 60; - while (iterations < max_iterations) : (iterations += 1) { + while (true) { // Carry hour/minute overflow explicitly so the candidate hour:minute // is checked against the bitfields *before* DST shifts it (croner // semantics: gap times fire shifted forward, same day). @@ -130,6 +130,9 @@ pub const CronExpression = struct { dt.day = n.day; dt.weekday = n.weekday; date_dirty = false; + // Impossible day/month combos (Feb 30, Apr 31) overflow to a + // non-matching month and loop forever; bail after 8 years. + if (dt.year - start_year > 8) return null; } // Check month @@ -181,8 +184,6 @@ pub const CronExpression = struct { } return result; } - - return null; } }; diff --git a/src/bun.js/rare_data.zig b/src/bun.js/rare_data.zig index e512b126af1d..814248b6a951 100644 --- a/src/bun.js/rare_data.zig +++ b/src/bun.js/rare_data.zig @@ -605,6 +605,7 @@ pub fn deinit(this: *RareData) void { } this.cleanup_hooks.clearAndFree(bun.default_allocator); + bun.debugAssert(this.cron_jobs.items.len == 0); this.cron_jobs.deinit(bun.default_allocator); this.path_buf.deinit(); diff --git a/src/bun.js/web_worker.zig b/src/bun.js/web_worker.zig index ce848f5e8d17..d88317bd2de1 100644 --- a/src/bun.js/web_worker.zig +++ b/src/bun.js/web_worker.zig @@ -603,8 +603,8 @@ pub fn exitAndDeinit(this: *WebWorker) noreturn { loop = vm.uwsLoop(); this.vm = null; vm.is_shutting_down = true; - jsc.API.cron.CronJob.clearAllForVM(vm, .teardown); vm.onExit(); + jsc.API.cron.CronJob.clearAllForVM(vm, .teardown); exit_code = vm.exit_handler.exit_code; globalObject = vm.global; vm_to_deinit = vm; diff --git a/test/js/bun/cron/cron-local-time.test.ts b/test/js/bun/cron/cron-local-time.test.ts index fb81b0c9aad1..10d651ff8bcb 100644 --- a/test/js/bun/cron/cron-local-time.test.ts +++ b/test/js/bun/cron/cron-local-time.test.ts @@ -91,28 +91,32 @@ describe.concurrent("Bun.cron.parse — DST transitions", () => { // Next valid 01:30 is the following day (EST): 2025-11-03 01:30 EST = 06:30 UTC. expect(next).toBe("2025-11-03T06:30:00.000Z"); }); -}); -describe.concurrent("Bun.cron(schedule, handler) — local time zone", () => { - test("registering 0 9 * * * computes the same next-fire as Bun.cron.parse in local time", async () => { - // The in-process scheduler uses the same next() — we verify via parse() since - // waiting for an actual fire would take up to 24 hours. - await using proc = Bun.spawn({ - cmd: [ - bunExe(), - "-e", - ` - const expr = "0 9 * * *"; - const parsed = Bun.cron.parse(expr).getTime(); - // Register and immediately stop; the deadline was computed from the same next(). - using job = Bun.cron(expr, () => {}); - process.stdout.write(String(parsed > Date.now())); - `, - ], - env: { ...bunEnv, TZ: "America/Los_Angeles" }, - }); - const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); - expect(stdout).toBe("true"); - expect(exitCode).toBe(0); + test("fall-back: wildcard hour skips the repeated hour (croner semantics)", async () => { + // After the first 1:00 (05:00Z), next() returns 2:00 (07:00Z), NOT the second 1:00 (06:00Z). + // Matches croner; cron-parser and Vixie fire through the repeated hour. + const next = await parseInTZ("America/New_York", "0 * * * *", "2025-11-02T05:00:01Z"); + expect(next).toBe("2025-11-02T07:00:00.000Z"); + }); + + test("spring-forward: only the first match in the gap fires shifted (croner semantics)", async () => { + // "*/15 2 * * *" has 4 occurrences in the missing hour. Bun fires the first + // shifted to 3:00, then skips to next day. cron-parser shifts all four. + const first = await parseInTZ("America/New_York", "*/15 2 * * *", "2025-03-09T06:59:00Z"); + expect(first).toBe("2025-03-09T07:00:00.000Z"); // 03:00 EDT + const second = await parseInTZ("America/New_York", "*/15 2 * * *", "2025-03-09T07:00:00Z"); + expect(second).toBe("2025-03-10T06:00:00.000Z"); // next day 02:00 EDT + }); + + test("Lord Howe: 30-minute spring-forward gap shifts by 30 min", async () => { + // Australia/Lord_Howe 2025-10-05 02:00→02:30. "15 2 * * *" → 02:45 LHDT. + const next = await parseInTZ("Australia/Lord_Howe", "15 2 * * *", "2025-10-04T14:30:00Z"); + expect(next).toBe("2025-10-04T15:45:00.000Z"); + }); + + test("Santiago: midnight spring-forward gap shifts to 01:00 same day", async () => { + // America/Santiago 2025-09-07 00:00→01:00. "0 0 * * *" → 01:00 CLST. + const next = await parseInTZ("America/Santiago", "0 0 * * *", "2025-09-06T23:00:00-04:00"); + expect(next).toBe("2025-09-07T04:00:00.000Z"); }); }); diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index ee440ded50c6..9d4611a230d4 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -162,19 +162,96 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { expect(thisInCallback).toBe(job); }, 70_000); - test("async callback delays next scheduling", async () => { + test("async callback: stop() during await prevents reschedule", async () => { + let fires = 0; const handler = Promise.withResolvers<void>(); const fire = Promise.withResolvers<void>(); using job = Bun.cron("* * * * *", async () => { + fires++; fire.resolve(); await handler.promise; }); await fire.promise; + expect(fires).toBe(1); job.stop(); handler.resolve(); - await Bun.sleep(10); + await Promise.resolve(); + expect(fires).toBe(1); + }, 70_000); + + test("unreferenced running job survives GC", async () => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + Bun.cron("* * * * *", () => { console.log("fired"); process.exit(0); }); + Bun.gc(true); + Bun.gc(true); + `, + ], + env: bunEnv, + stderr: "pipe", + }); + const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stdout.trim()).toBe("fired"); + expect(exitCode).toBe(0); + }, 70_000); + + test("ref() after stop() does not keep process alive", async () => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + const job = Bun.cron("* * * * *", () => {}); + job.stop(); + job.ref(); + console.log("done"); + `, + ], + env: bunEnv, + stderr: "pipe", + }); + const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stdout.trim()).toBe("done"); + expect(exitCode).toBe(0); + }); + + test("worker terminate while async callback pending releases cleanly", async () => { + using dir = tempDir("cron-worker", { + "worker.ts": ` + let fired = false; + Bun.cron("* * * * *", async () => { + fired = true; + self.postMessage("fired"); + await new Promise(() => {}); // never settles + }); + `, + }); + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + const w = new Worker("./worker.ts"); + w.onmessage = () => { + w.terminate(); + Bun.gc(true); + console.log("ok"); + process.exit(0); + }; + `, + ], + env: bunEnv, + cwd: String(dir), + stderr: "pipe", + }); + const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stdout.trim()).toBe("ok"); + expect(exitCode).toBe(0); }, 70_000); test("sync throw in callback emits uncaughtException", async () => { From b297206cd8ba242c39cf7c27368944641d78704f Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 14:02:09 -0700 Subject: [PATCH 41/58] cron: fall-back wild schedules fire through repeated hour (cronie semantics) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Schedules with * minute or * hour now fire through both occurrences of the fall-back duplicated hour, matching crontab/cronie and cron-parser. Fixed-time schedules (e.g. 30 1 * * *) still fire once at the first occurrence. Implemented as a bounded real-time scan (≤121 minutes) before returning the wall-clock result, fast-pathed away when result is the immediate next minute. Spring-forward behavior unchanged. --- docs/runtime/cron.mdx | 6 ++--- packages/bun-types/bun.d.ts | 6 ++--- src/bun.js/api/cron_parser.zig | 33 +++++++++++++++++++++--- test/js/bun/cron/cron-local-time.test.ts | 14 +++++++--- 4 files changed, 45 insertions(+), 14 deletions(-) diff --git a/docs/runtime/cron.mdx b/docs/runtime/cron.mdx index 89131be591a1..3f37ff2c024c 100644 --- a/docs/runtime/cron.mdx +++ b/docs/runtime/cron.mdx @@ -122,12 +122,10 @@ Schedules are interpreted in the system's **local time zone** — the same way c To use UTC, set `TZ=UTC` in the environment. -DST transitions follow ECMAScript `Date` semantics (matching the npm `croner` package): +DST transitions: - **Spring-forward** — a schedule that lands in the missing hour fires that day, shifted forward by the gap (e.g. `30 2 * * *` runs at 3:30 on the spring-forward day). For multi-minute patterns inside the gap (`*/15 2 * * *`), only the first match fires. -- **Fall-back** — a schedule in the duplicated hour fires once, at the first occurrence. Wildcard schedules (`* * * * *`, `0 * * * *`) also fire once per wall-clock minute, so the repeated hour is skipped in real time. - -This differs from Vixie cron (which runs gap jobs immediately at the end of the gap) and `cron-parser` (which fires through the repeated fall-back hour). +- **Fall-back** — a fixed-time schedule in the duplicated hour (`30 1 * * *`) fires once, at the first occurrence. A schedule whose minute or hour field is `*` (`0 * * * *`, `* * * * *`) fires through **both** occurrences — once per real-time minute, matching crontab on Linux. ### Day-of-month and day-of-week interaction diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index 45eab4ad549a..b42c063d223a 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7603,9 +7603,9 @@ declare module "bun" { * matching uses OR logic per [POSIX cron](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html): * a date matches if **either** field matches. * - * DST: schedules follow ECMAScript `Date` semantics (matching `croner`) — - * spring-forward times shift forward by the gap; fall-back times fire once - * at the first occurrence. + * DST: spring-forward times shift forward by the gap; in the fall-back + * duplicated hour, fixed-time schedules fire once (first occurrence) while + * schedules with `*` minute or hour fire through both occurrences. * * @param expression - A cron expression or nickname (e.g. `"0,15,30,45 * * * *"`, `"0 9 * * MON-FRI"`, `"@hourly"`) * @param relativeDate - Starting point for the search (defaults to `Date.now()`). Accepts a `Date` or milliseconds since epoch. diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index a1096082f460..083e40a33afc 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -94,12 +94,28 @@ pub const CronExpression = struct { return stream.getWritten(); } + /// Check if a real instant matches all five fields in local time. + fn matchesInstant(self: CronExpression, globalObject: *jsc.JSGlobalObject, ms: f64) bool { + const t = globalObject.msToGregorianDateTime(ms); + if (!bitSet(u64, self.minutes, @intCast(t.minute))) return false; + if (!bitSet(u32, self.hours, @intCast(t.hour))) return false; + if (!bitSet(u16, self.months, @intCast(t.month))) return false; + const day_ok = bitSet(u32, self.days, @intCast(t.day)); + const weekday_ok = bitSet(u8, self.weekdays, @intCast(t.weekday)); + const both_restricted = !self.days_is_wildcard and !self.weekdays_is_wildcard; + return if (both_restricted) (day_ok or weekday_ok) else (day_ok and weekday_ok); + } + /// Compute the next time (in ms since epoch) that matches this expression /// in the system's local time zone, starting from `from_ms`. Returns null /// if no match found within 8 years. pub fn next(self: CronExpression, globalObject: *jsc.JSGlobalObject, from_ms: f64) bun.JSError!?f64 { var dt = globalObject.msToGregorianDateTime(from_ms); const start_year = dt.year; + // cronie: schedules with `*` minute or `*` hour run through a fall-back + // repeated hour; fixed-time schedules fire once. We use the semantic + // check (all bits set) so `*/1` counts as wild — matches the npm camp. + const wild = self.minutes == all_minutes or self.hours == all_hours; dt.minute += 1; dt.second = 0; @@ -175,9 +191,19 @@ pub const CronExpression = struct { // All fields match const result = try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0); - // During DST fall-back, gregorianDateTimeToMS picks the first - // occurrence of an ambiguous local time. If from_ms is already past - // it (in the second occurrence), keep searching. + // During DST fall-back, gregorianDateTimeToMS picks the FORMER + // occurrence of an ambiguous local time, and the wall-clock walk + // above can step over the entire second occurrence. For wild + // schedules, scan real-time minutes between from_ms and result + // (capped at 2h, the largest real-world DST shift) for an earlier + // match in the repeated window. + if (wild and result > from_ms + 60_000) { + var probe = (@floor(from_ms / 60_000) + 1) * 60_000; + const cap = @min(result, from_ms + 121 * 60_000); + while (probe < cap) : (probe += 60_000) { + if (self.matchesInstant(globalObject, probe)) return probe; + } + } if (result <= from_ms) { dt.minute += 1; continue; @@ -191,6 +217,7 @@ pub const CronExpression = struct { // Name lookup tables // ============================================================================ +const all_minutes: u64 = (1 << 60) - 1; const all_hours: u32 = (1 << 24) - 1; const all_days: u32 = ((1 << 32) - 1) & ~@as(u32, 1); const all_months: u16 = ((1 << 13) - 1) & ~@as(u16, 1); diff --git a/test/js/bun/cron/cron-local-time.test.ts b/test/js/bun/cron/cron-local-time.test.ts index 10d651ff8bcb..4bab6596653a 100644 --- a/test/js/bun/cron/cron-local-time.test.ts +++ b/test/js/bun/cron/cron-local-time.test.ts @@ -92,11 +92,17 @@ describe.concurrent("Bun.cron.parse — DST transitions", () => { expect(next).toBe("2025-11-03T06:30:00.000Z"); }); - test("fall-back: wildcard hour skips the repeated hour (croner semantics)", async () => { - // After the first 1:00 (05:00Z), next() returns 2:00 (07:00Z), NOT the second 1:00 (06:00Z). - // Matches croner; cron-parser and Vixie fire through the repeated hour. + test("fall-back: wildcard hour fires through both occurrences (cronie semantics)", async () => { + // After the first 1:00 (05:00Z), next() returns the SECOND 1:00 (06:00Z). + // Matches cronie/Vixie and cron-parser. Fixed-time schedules (30 1 * * *) + // still fire once — only `*` minute or `*` hour schedules run through. const next = await parseInTZ("America/New_York", "0 * * * *", "2025-11-02T05:00:01Z"); - expect(next).toBe("2025-11-02T07:00:00.000Z"); + expect(next).toBe("2025-11-02T06:00:00.000Z"); + }); + + test("fall-back: every-minute fires through both occurrences", async () => { + const next = await parseInTZ("America/New_York", "* * * * *", "2025-11-02T05:59:01Z"); + expect(next).toBe("2025-11-02T06:00:00.000Z"); }); test("spring-forward: only the first match in the gap fires shifted (croner semantics)", async () => { From ef368f69ba137efe542687346eb9b018bf9543ba Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 14:08:44 -0700 Subject: [PATCH 42/58] =?UTF-8?q?cron:=20simplify=20=E2=80=94=20extract=20?= =?UTF-8?q?matchesDay,=20dedupe=20all=5F*=20constants,=20name=20scan=20con?= =?UTF-8?q?stants,=20sync=20docs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/runtime/cron.mdx | 10 +++---- packages/bun-types/bun.d.ts | 2 +- src/bun.js/api/cron.zig | 13 ++++----- src/bun.js/api/cron_parser.zig | 52 ++++++++++++++++++---------------- 4 files changed, 39 insertions(+), 38 deletions(-) diff --git a/docs/runtime/cron.mdx b/docs/runtime/cron.mdx index 3f37ff2c024c..5e8120d29dfc 100644 --- a/docs/runtime/cron.mdx +++ b/docs/runtime/cron.mdx @@ -48,7 +48,7 @@ console.log(next); // => next quarter-hour boundary ### Returns -`Date | null` — the next matching time, or `null` if no match exists within ~4 years (e.g. February 30th). +`Date | null` — the next matching time, or `null` if no match exists within 8 years (e.g. February 30th). ### Chaining calls @@ -162,10 +162,10 @@ This is the lightweight option for long-running servers and workers — no syste ### Parameters -| Parameter | Type | Description | -| ---------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------- | -| `schedule` | `string` | A [cron expression](#cron-expression-syntax) or nickname like `"@hourly"`. | -| `handler` | `(this: CronJob) => void \| Promise<void>` | Called on each fire. Inside a `function` callback, `this` is the `CronJob` (so `this.stop()` works). | +| Parameter | Type | Description | +| ---------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `schedule` | `string` | A [cron expression](#cron-expression-syntax) or nickname like `"@hourly"`. | +| `handler` | `(this: CronJob) => unknown` | Called on each fire. May return a Promise — the next fire is not scheduled until it settles. Inside a `function` callback, `this` is the `CronJob` (so `this.stop()` works). | Returns a [`CronJob`](#the-cronjob-handle) synchronously. Throws a `TypeError` if the expression is invalid or has no future occurrences (e.g. `"0 0 30 2 *"` — February 30th). diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index b42c063d223a..d347ffa7cac5 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7609,7 +7609,7 @@ declare module "bun" { * * @param expression - A cron expression or nickname (e.g. `"0,15,30,45 * * * *"`, `"0 9 * * MON-FRI"`, `"@hourly"`) * @param relativeDate - Starting point for the search (defaults to `Date.now()`). Accepts a `Date` or milliseconds since epoch. - * @returns The next `Date` matching the expression in local time, or `null` if no match exists within ~4 years (e.g. `"0 0 30 2 *"` — Feb 30 never occurs) + * @returns The next `Date` matching the expression in local time, or `null` if no match exists within 8 years (e.g. `"0 0 30 2 *"` — Feb 30 never occurs) * @throws If the expression is invalid or `relativeDate` is `NaN`/`Infinity` * * @example diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index f4ccf5ebf71d..a251c0de490f 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -1475,13 +1475,9 @@ fn cronToTaskXml( // Use semantic checks (bitfield values) not syntax flags for wildcard detection. // e.g. "*/1" sets all bits just like "*" but has _is_wildcard=false. - const all_days: u32 = ((1 << 32) - 1) & ~@as(u32, 1); // bits 1-31 - const all_months: u16 = ((1 << 13) - 1) & ~@as(u16, 1); // bits 1-12 - const all_weekdays: u8 = (1 << 7) - 1; // bits 0-6 - - const days_is_wild = cron.days == all_days; - const weekdays_is_wild = cron.weekdays == all_weekdays; - const months_is_wild = cron.months == all_months; + const days_is_wild = cron.days == cron_parser.all_days; + const weekdays_is_wild = cron.weekdays == cron_parser.all_weekdays; + const months_is_wild = cron.months == cron_parser.all_months; // Try to use a single trigger with Repetition for simple repeating patterns. // This avoids the 48-trigger limit for high-frequency expressions. @@ -1751,7 +1747,8 @@ fn makeTempPath(comptime prefix: []const u8, title: []const u8) ![:0]const u8 { } const std = @import("std"); -const CronExpression = @import("./cron_parser.zig").CronExpression; +const cron_parser = @import("./cron_parser.zig"); +const CronExpression = cron_parser.CronExpression; const bun = @import("bun"); const jsc = bun.jsc; diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index 083e40a33afc..c7d6712200c2 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -94,16 +94,24 @@ pub const CronExpression = struct { return stream.getWritten(); } + /// POSIX cron: if both DOM and DOW are restricted (not `*`), match either; + /// otherwise match both (a `*` field matches all anyway). + fn matchesDay(self: CronExpression, day: i32, weekday: i32) bool { + const day_ok = bitSet(u32, self.days, @intCast(day)); + const weekday_ok = bitSet(u8, self.weekdays, @intCast(weekday)); + return if (!self.days_is_wildcard and !self.weekdays_is_wildcard) + day_ok or weekday_ok + else + day_ok and weekday_ok; + } + /// Check if a real instant matches all five fields in local time. fn matchesInstant(self: CronExpression, globalObject: *jsc.JSGlobalObject, ms: f64) bool { const t = globalObject.msToGregorianDateTime(ms); - if (!bitSet(u64, self.minutes, @intCast(t.minute))) return false; - if (!bitSet(u32, self.hours, @intCast(t.hour))) return false; - if (!bitSet(u16, self.months, @intCast(t.month))) return false; - const day_ok = bitSet(u32, self.days, @intCast(t.day)); - const weekday_ok = bitSet(u8, self.weekdays, @intCast(t.weekday)); - const both_restricted = !self.days_is_wildcard and !self.weekdays_is_wildcard; - return if (both_restricted) (day_ok or weekday_ok) else (day_ok and weekday_ok); + return bitSet(u64, self.minutes, @intCast(t.minute)) and + bitSet(u32, self.hours, @intCast(t.hour)) and + bitSet(u16, self.months, @intCast(t.month)) and + self.matchesDay(t.day, t.weekday); } /// Compute the next time (in ms since epoch) that matches this expression @@ -161,14 +169,7 @@ pub const CronExpression = struct { continue; } - // POSIX cron day-of-month / day-of-week logic: - // - If both are restricted (neither was *): OR — either matching is enough - // - If only one is restricted: only that one matters (the * field matches all) - const day_ok = bitSet(u32, self.days, @intCast(dt.day)); - const weekday_ok = bitSet(u8, self.weekdays, @intCast(dt.weekday)); - const both_restricted = !self.days_is_wildcard and !self.weekdays_is_wildcard; - const day_match = if (both_restricted) (day_ok or weekday_ok) else (day_ok and weekday_ok); - if (!day_match) { + if (!self.matchesDay(dt.day, dt.weekday)) { dt.day += 1; dt.hour = 0; dt.minute = 0; @@ -197,10 +198,10 @@ pub const CronExpression = struct { // schedules, scan real-time minutes between from_ms and result // (capped at 2h, the largest real-world DST shift) for an earlier // match in the repeated window. - if (wild and result > from_ms + 60_000) { - var probe = (@floor(from_ms / 60_000) + 1) * 60_000; - const cap = @min(result, from_ms + 121 * 60_000); - while (probe < cap) : (probe += 60_000) { + if (wild and result > from_ms + minute_ms) { + var probe = (@floor(from_ms / minute_ms) + 1) * minute_ms; + const cap = @min(result, from_ms + (max_dst_shift_min + 1) * minute_ms); + while (probe < cap) : (probe += minute_ms) { if (self.matchesInstant(globalObject, probe)) return probe; } } @@ -217,11 +218,14 @@ pub const CronExpression = struct { // Name lookup tables // ============================================================================ -const all_minutes: u64 = (1 << 60) - 1; -const all_hours: u32 = (1 << 24) - 1; -const all_days: u32 = ((1 << 32) - 1) & ~@as(u32, 1); -const all_months: u16 = ((1 << 13) - 1) & ~@as(u16, 1); -const all_weekdays: u8 = (1 << 7) - 1; +const minute_ms: f64 = 60_000; +const max_dst_shift_min: f64 = 120; + +pub const all_minutes: u64 = (1 << 60) - 1; +pub const all_hours: u32 = (1 << 24) - 1; +pub const all_days: u32 = ((1 << 32) - 1) & ~@as(u32, 1); +pub const all_months: u16 = ((1 << 13) - 1) & ~@as(u16, 1); +pub const all_weekdays: u8 = (1 << 7) - 1; fn parseNickname(expr: []const u8) ?CronExpression { const eql = bun.strings.eqlCaseInsensitiveASCIIICheckLength; From 7d659e51f7b9d72d9c39e99672778b3e72b4dffc Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Thu, 2 Apr 2026 21:10:28 +0000 Subject: [PATCH 43/58] [autofix.ci] apply automated fixes --- src/bun.js/api/cron.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index a251c0de490f..f8f10b92bbb9 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -1747,6 +1747,7 @@ fn makeTempPath(comptime prefix: []const u8, title: []const u8) ![:0]const u8 { } const std = @import("std"); + const cron_parser = @import("./cron_parser.zig"); const CronExpression = cron_parser.CronExpression; From 143420bfaecd4cdf5f139709f849fabda0ec2596 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 14:21:32 -0700 Subject: [PATCH 44/58] =?UTF-8?q?cron:=20deep-simplify=20=E2=80=94=20handl?= =?UTF-8?q?eOom=20ladders,=20merge=20C++=20date=20externs,=20fix=20allocPr?= =?UTF-8?q?intZ=20double-alloc,=20popCount=20in=20formatBitfield?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -51 net lines. allocPrintZ now uses std.fmt.allocPrintSentinel (one allocation instead of two). Bun__gregorianDateTimeToMS and Bun__msToGregorianDateTime each take a bool localTime parameter, deleting the UTC duplicates. --- src/bun.js/api/cron.zig | 56 +++++++++----------------- src/bun.js/api/cron_parser.zig | 9 +---- src/bun.js/bindings/JSGlobalObject.zig | 8 ++-- src/bun.js/bindings/bindings.cpp | 36 ++--------------- 4 files changed, 29 insertions(+), 80 deletions(-) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index f8f10b92bbb9..89edecbf12b6 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -241,7 +241,7 @@ pub const CronRegisterJob = struct { return; }; - const tmp_path = makeTempPath("bun-cron-", this.title) catch { + const tmp_path = makeTempPath("bun-cron-") catch { this.setErr("Out of memory", .{}); this.finish(); return; @@ -471,30 +471,17 @@ pub const CronRegisterJob = struct { bun.default_allocator.free(abs_path); return globalObject.throw("Failed to get bun executable path", .{}); }; - const schedule_owned = bun.default_allocator.dupeZ(u8, normalized_schedule) catch { - bun.default_allocator.free(abs_path); - return globalObject.throw("Out of memory", .{}); - }; - const raw_schedule_owned = bun.default_allocator.dupeZ(u8, schedule_slice.slice()) catch { - bun.default_allocator.free(abs_path); - bun.default_allocator.free(schedule_owned); - return globalObject.throw("Out of memory", .{}); - }; - const title_owned = bun.default_allocator.dupeZ(u8, title_slice.slice()) catch { - bun.default_allocator.free(abs_path); - bun.default_allocator.free(schedule_owned); - bun.default_allocator.free(raw_schedule_owned); - return globalObject.throw("Out of memory", .{}); - }; - - const job = bun.default_allocator.create(CronRegisterJob) catch { - bun.default_allocator.free(abs_path); - bun.default_allocator.free(schedule_owned); - bun.default_allocator.free(raw_schedule_owned); - bun.default_allocator.free(title_owned); - return globalObject.throw("Out of memory", .{}); + const job = bun.handleOom(bun.default_allocator.create(CronRegisterJob)); + job.* = .{ + .global = globalObject, + .bun_exe = bun_exe, + .abs_path = abs_path, + .schedule = bun.handleOom(bun.default_allocator.dupeZ(u8, normalized_schedule)), + .raw_schedule = bun.handleOom(bun.default_allocator.dupeZ(u8, schedule_slice.slice())), + .title = bun.handleOom(bun.default_allocator.dupeZ(u8, title_slice.slice())), + .parsed_cron = parsed, + .promise = jsc.JSPromise.Strong.init(globalObject), }; - job.* = .{ .global = globalObject, .bun_exe = bun_exe, .abs_path = abs_path, .schedule = schedule_owned, .raw_schedule = raw_schedule_owned, .title = title_owned, .parsed_cron = parsed, .promise = jsc.JSPromise.Strong.init(globalObject) }; const promise_value = job.promise.value(); job.poll.ref(jsc.VirtualMachine.get()); @@ -532,7 +519,7 @@ pub const CronRegisterJob = struct { }; defer bun.default_allocator.free(xml); - const xml_path = makeTempPath("bun-cron-xml-", this.title) catch { + const xml_path = makeTempPath("bun-cron-xml-") catch { this.setErr("Out of memory", .{}); this.finish(); return; @@ -728,7 +715,7 @@ pub const CronRemoveJob = struct { return; }; - const tmp_path = makeTempPath("bun-cron-rm-", this.title) catch { + const tmp_path = makeTempPath("bun-cron-rm-") catch { this.setErr("Out of memory", .{}); this.finish(); return; @@ -783,12 +770,12 @@ pub const CronRemoveJob = struct { if (!validateTitle(title_slice.slice())) return globalObject.throwInvalidArguments("Cron title must contain only alphanumeric characters, hyphens, and underscores", .{}); - const title_owned = bun.default_allocator.dupeZ(u8, title_slice.slice()) catch return globalObject.throw("Out of memory", .{}); - const job = bun.default_allocator.create(CronRemoveJob) catch { - bun.default_allocator.free(title_owned); - return globalObject.throw("Out of memory", .{}); + const job = bun.handleOom(bun.default_allocator.create(CronRemoveJob)); + job.* = .{ + .global = globalObject, + .title = bun.handleOom(bun.default_allocator.dupeZ(u8, title_slice.slice())), + .promise = jsc.JSPromise.Strong.init(globalObject), }; - job.* = .{ .global = globalObject, .title = title_owned, .promise = jsc.JSPromise.Strong.init(globalObject) }; const promise_value = job.promise.value(); job.poll.ref(jsc.VirtualMachine.get()); @@ -1733,14 +1720,11 @@ fn computeStepInterval(comptime T: type, bits: T, _: u7, max: u7) ?u32 { } fn allocPrintZ(allocator: std.mem.Allocator, comptime fmt: []const u8, args: anytype) std.mem.Allocator.Error![:0]const u8 { - const slice = try std.fmt.allocPrint(allocator, fmt, args); - defer allocator.free(slice); - return allocator.dupeZ(u8, slice); + return std.fmt.allocPrintSentinel(allocator, fmt, args, 0); } /// Create a temp file path with a random suffix to avoid TOCTOU/symlink attacks. -fn makeTempPath(comptime prefix: []const u8, title: []const u8) ![:0]const u8 { - _ = title; +fn makeTempPath(comptime prefix: []const u8) ![:0]const u8 { var name_buf: bun.PathBuffer = undefined; const name = bun.fs.FileSystem.tmpname(prefix ++ "tmp", &name_buf, bun.fastRandom()) catch return error.OutOfMemory; return bun.default_allocator.dupeZ(u8, bun.path.joinAbsString(bun.fs.FileSystem.RealFS.platformTempDir(), &.{name}, .auto)); diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index c7d6712200c2..eedaf7757ac7 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -352,14 +352,7 @@ inline fn bitSet(comptime T: type, set: T, pos: std.math.Log2Int(T)) bool { /// Write a bitfield as a cron field string: "*" if all bits set, or comma-separated values. fn formatBitfield(w: anytype, comptime T: type, bits: T, min: u8, max: u8) void { - var all_set = true; - for (min..max + 1) |i| { - if ((bits >> @intCast(i)) & 1 == 0) { - all_set = false; - break; - } - } - if (all_set) { + if (@popCount(bits) == @as(u32, max) - min + 1) { w.writeByte('*') catch unreachable; return; } diff --git a/src/bun.js/bindings/JSGlobalObject.zig b/src/bun.js/bindings/JSGlobalObject.zig index b32a73f53e0c..2e3d6cc1640a 100644 --- a/src/bun.js/bindings/JSGlobalObject.zig +++ b/src/bun.js/bindings/JSGlobalObject.zig @@ -24,12 +24,12 @@ pub const JSGlobalObject = opaque { } pub fn gregorianDateTimeToMS(this: *jsc.JSGlobalObject, year: i32, month: i32, day: i32, hour: i32, minute: i32, second: i32, millisecond: i32) bun.JSError!f64 { jsc.markBinding(@src()); - return bun.cpp.Bun__gregorianDateTimeToMS(this, year, month, day, hour, minute, second, millisecond); + return bun.cpp.Bun__gregorianDateTimeToMS(this, year, month, day, hour, minute, second, millisecond, true); } pub fn gregorianDateTimeToMSUTC(this: *jsc.JSGlobalObject, year: i32, month: i32, day: i32, hour: i32, minute: i32, second: i32, millisecond: i32) bun.JSError!f64 { jsc.markBinding(@src()); - return bun.cpp.Bun__gregorianDateTimeToMSUTC(this, year, month, day, hour, minute, second, millisecond); + return bun.cpp.Bun__gregorianDateTimeToMS(this, year, month, day, hour, minute, second, millisecond, false); } pub const GregorianDateTime = struct { @@ -45,14 +45,14 @@ pub const JSGlobalObject = opaque { pub fn msToGregorianDateTimeUTC(this: *jsc.JSGlobalObject, ms: f64) GregorianDateTime { jsc.markBinding(@src()); var dt: GregorianDateTime = undefined; - bun.cpp.Bun__msToGregorianDateTimeUTC(this, ms, &dt.year, &dt.month, &dt.day, &dt.hour, &dt.minute, &dt.second, &dt.weekday); + bun.cpp.Bun__msToGregorianDateTime(this, ms, false, &dt.year, &dt.month, &dt.day, &dt.hour, &dt.minute, &dt.second, &dt.weekday); return dt; } pub fn msToGregorianDateTime(this: *jsc.JSGlobalObject, ms: f64) GregorianDateTime { jsc.markBinding(@src()); var dt: GregorianDateTime = undefined; - bun.cpp.Bun__msToGregorianDateTime(this, ms, &dt.year, &dt.month, &dt.day, &dt.hour, &dt.minute, &dt.second, &dt.weekday); + bun.cpp.Bun__msToGregorianDateTime(this, ms, true, &dt.year, &dt.month, &dt.day, &dt.hour, &dt.minute, &dt.second, &dt.weekday); return dt; } diff --git a/src/bun.js/bindings/bindings.cpp b/src/bun.js/bindings/bindings.cpp index b7c2ef933d66..030dc96f2f08 100644 --- a/src/bun.js/bindings/bindings.cpp +++ b/src/bun.js/bindings/bindings.cpp @@ -5759,7 +5759,7 @@ extern "C" [[ZIG_EXPORT(check_slow)]] double Bun__parseDate(JSC::JSGlobalObject* return vm.dateCache.parseDate(globalObject, vm, str->toWTFString()); } -extern "C" [[ZIG_EXPORT(check_slow)]] double Bun__gregorianDateTimeToMS(JSC::JSGlobalObject* globalObject, int year, int month, int day, int hour, int minute, int second, int millisecond) +extern "C" [[ZIG_EXPORT(check_slow)]] double Bun__gregorianDateTimeToMS(JSC::JSGlobalObject* globalObject, int year, int month, int day, int hour, int minute, int second, int millisecond, bool localTime) { auto& vm = JSC::getVM(globalObject); WTF::GregorianDateTime dateTime; @@ -5769,43 +5769,15 @@ extern "C" [[ZIG_EXPORT(check_slow)]] double Bun__gregorianDateTimeToMS(JSC::JSG dateTime.setHour(hour); dateTime.setMinute(minute); dateTime.setSecond(second); - return vm.dateCache.gregorianDateTimeToMS(dateTime, millisecond, WTF::TimeType::LocalTime); + return vm.dateCache.gregorianDateTimeToMS(dateTime, millisecond, localTime ? WTF::TimeType::LocalTime : WTF::TimeType::UTCTime); } -extern "C" [[ZIG_EXPORT(check_slow)]] double Bun__gregorianDateTimeToMSUTC(JSC::JSGlobalObject* globalObject, int year, int month, int day, int hour, int minute, int second, int millisecond) -{ - auto& vm = JSC::getVM(globalObject); - WTF::GregorianDateTime dateTime; - dateTime.setYear(year); - dateTime.setMonth(month - 1); - dateTime.setMonthDay(day); - dateTime.setHour(hour); - dateTime.setMinute(minute); - dateTime.setSecond(second); - return vm.dateCache.gregorianDateTimeToMS(dateTime, millisecond, WTF::TimeType::UTCTime); -} - -extern "C" [[ZIG_EXPORT(nothrow)]] void Bun__msToGregorianDateTimeUTC(JSC::JSGlobalObject* globalObject, double ms, - int* year, int* month, int* day, int* hour, int* minute, int* second, int* weekday) -{ - auto& vm = JSC::getVM(globalObject); - WTF::GregorianDateTime dt; - vm.dateCache.msToGregorianDateTime(ms, WTF::TimeType::UTCTime, dt); - *year = dt.year(); - *month = dt.month() + 1; - *day = dt.monthDay(); - *hour = dt.hour(); - *minute = dt.minute(); - *second = dt.second(); - *weekday = dt.weekDay(); -} - -extern "C" [[ZIG_EXPORT(nothrow)]] void Bun__msToGregorianDateTime(JSC::JSGlobalObject* globalObject, double ms, +extern "C" [[ZIG_EXPORT(nothrow)]] void Bun__msToGregorianDateTime(JSC::JSGlobalObject* globalObject, double ms, bool localTime, int* year, int* month, int* day, int* hour, int* minute, int* second, int* weekday) { auto& vm = JSC::getVM(globalObject); WTF::GregorianDateTime dt; - vm.dateCache.msToGregorianDateTime(ms, WTF::TimeType::LocalTime, dt); + vm.dateCache.msToGregorianDateTime(ms, localTime ? WTF::TimeType::LocalTime : WTF::TimeType::UTCTime, dt); *year = dt.year(); *month = dt.month() + 1; *day = dt.monthDay(); From 97b8a59e248669adef8a4195613b711e6e38575e Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 15:01:10 -0700 Subject: [PATCH 45/58] cron: --hot test writes markers outside watched dir (avoid watcher/exit ASAN race) The watcher thread receives inotify events for marker file writes; if a write happens immediately before process.exit(0), bustDirCache races BSS poisoning. Markers now live in a sibling tempDir that --hot doesn't watch. --- test/js/bun/cron/in-process-cron.test.ts | 27 ++++++++++++++---------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index 9d4611a230d4..06cc7e8c1a51 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -349,50 +349,55 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { }, 70_000); test("--hot reload clears jobs deleted from source", async () => { + // Markers live OUTSIDE the --hot-watched dir so inotify doesn't deliver + // a write event that races process.exit() teardown (watcher/exit race). + using markers = tempDir("cron-hot-markers", {}); + const m = (f: string) => join(String(markers), f); using dir = tempDir("cron-hot", { "app.ts": ` import { writeFileSync, existsSync } from "node:fs"; - writeFileSync("v1.evaluated", ""); + const m = process.env.MARKERS; + writeFileSync(m + "/v1.evaluated", ""); // A fire before the v2 reload is legitimate (not a ghost) — only // write the marker if v2 has already evaluated. Bun.cron("* * * * *", () => { - if (existsSync("v2.evaluated")) writeFileSync("ghost.fired", ""); + if (existsSync(m + "/v2.evaluated")) writeFileSync(m + "/ghost.fired", ""); }); `, }); - const path = (f: string) => join(String(dir), f); await using proc = Bun.spawn({ cmd: [bunExe(), "--hot", "--no-clear-screen", "app.ts"], - env: bunEnv, + env: { ...bunEnv, MARKERS: String(markers) }, cwd: String(dir), stdout: "ignore", stderr: "pipe", }); const stderrP = proc.stderr.text(); - while (!(await Bun.file(path("v1.evaluated")).exists())) await Bun.sleep(10); + while (!(await Bun.file(m("v1.evaluated")).exists())) await Bun.sleep(10); // Delete the ghost cron; replace with a sentinel that fires on the same // boundary. When the sentinel fires, ghost.fired must NOT exist. await Bun.write( - path("app.ts"), + join(String(dir), "app.ts"), ` import { writeFileSync, existsSync } from "node:fs"; - writeFileSync("v2.evaluated", ""); + const m = process.env.MARKERS; + writeFileSync(m + "/v2.evaluated", ""); Bun.cron("* * * * *", () => { - writeFileSync("result", existsSync("ghost.fired") ? "GHOST_FIRED" : "ok"); + writeFileSync(m + "/result", existsSync(m + "/ghost.fired") ? "GHOST_FIRED" : "ok"); process.exit(0); }); `, ); - while (!(await Bun.file(path("v2.evaluated")).exists())) await Bun.sleep(10); + while (!(await Bun.file(m("v2.evaluated")).exists())) await Bun.sleep(10); const [exitCode, stderr] = await Promise.all([proc.exited, stderrP]); if (exitCode !== 0) console.error(stderr); expect(exitCode).toBe(0); - expect(await Bun.file(path("result")).text()).toBe("ok"); - expect(await Bun.file(path("ghost.fired")).exists()).toBe(false); + expect(await Bun.file(m("result")).text()).toBe("ok"); + expect(await Bun.file(m("ghost.fired")).exists()).toBe(false); }, 130_000); }); From 6a9b1d61c65da41617f7bcb7387746b095200407 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 15:14:10 -0700 Subject: [PATCH 46/58] cron_parser: hoist year bound into loop condition --- src/bun.js/api/cron_parser.zig | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index eedaf7757ac7..f59635d279d6 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -128,8 +128,11 @@ pub const CronExpression = struct { dt.minute += 1; dt.second = 0; + // dt.year only changes inside the date-normalize block (gated on + // date_dirty), but hour overflow forces date_dirty within ≤1440 + // iterations, so this check is reached and the loop is bounded. var date_dirty = true; - while (true) { + while (dt.year - start_year <= 8) { // Carry hour/minute overflow explicitly so the candidate hour:minute // is checked against the bitfields *before* DST shifts it (croner // semantics: gap times fire shifted forward, same day). @@ -154,9 +157,6 @@ pub const CronExpression = struct { dt.day = n.day; dt.weekday = n.weekday; date_dirty = false; - // Impossible day/month combos (Feb 30, Apr 31) overflow to a - // non-matching month and loop forever; bail after 8 years. - if (dt.year - start_year > 8) return null; } // Check month @@ -211,6 +211,7 @@ pub const CronExpression = struct { } return result; } + return null; } }; From 3e0005ebb6e926bfbb8b04a1181c09fd4bfb1df3 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 15:42:44 -0700 Subject: [PATCH 47/58] cron: fix WindowsBufferedReader.deinit pipe leak; clearAllForVM in main VM deinit WindowsBufferedReader.deinit nulled this.source before calling closeImpl, but closeImpl re-reads this.source and skips cleanup when null. Reordered so closeImpl sees the source (it nulls it itself at :1175). VirtualMachine.deinit now calls clearAllForVM(.teardown) before rare_data.deinit so the cron_jobs.len==0 debugAssert holds for the main VM, matching the worker path. --- src/bun.js/VirtualMachine.zig | 1 + src/io/PipeReader.zig | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/bun.js/VirtualMachine.zig b/src/bun.js/VirtualMachine.zig index 316129cedfb2..e183b3bc257e 100644 --- a/src/bun.js/VirtualMachine.zig +++ b/src/bun.js/VirtualMachine.zig @@ -1996,6 +1996,7 @@ pub fn deinit(this: *VirtualMachine) void { } this.source_mappings.deinit(); if (this.rare_data) |rare_data| { + jsc.API.cron.CronJob.clearAllForVM(this, .teardown); rare_data.deinit(); } this.overridden_main.deinit(); diff --git a/src/io/PipeReader.zig b/src/io/PipeReader.zig index 9e18d789953b..2f3586e56ed4 100644 --- a/src/io/PipeReader.zig +++ b/src/io/PipeReader.zig @@ -760,7 +760,7 @@ pub const WindowsBufferedReader = struct { return Type.onReaderError(@as(*Type, @ptrCast(@alignCast(this))), err); } fn loop(this: *anyopaque) *Async.Loop { - return Type.loop(@as(*Type, @alignCast(@ptrCast(this)))); + return Type.loop(@as(*Type, @ptrCast(@alignCast(this)))); } }; return .{ @@ -937,11 +937,11 @@ pub const WindowsBufferedReader = struct { MaxBuf.removeFromPipereader(&this.maxbuf); this.buffer().deinit(); const source = this.source orelse return; - this.source = null; if (!source.isClosed()) { - // closeImpl will take care of freeing the source + // closeImpl reads this.source; null it after. this.closeImpl(false); } + this.source = null; } pub fn setRawMode(this: *WindowsBufferedReader, value: bool) bun.sys.Maybe(void) { From 7b64fa687d781f6cd77a581957ec6f5e0f86a857 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 16:04:46 -0700 Subject: [PATCH 48/58] =?UTF-8?q?cron=5Fparser:=20drop=20date=5Fdirty=20?= =?UTF-8?q?=E2=80=94=20noon=20round-trip=20is=20cheap=20(dateCache),=20sim?= =?UTF-8?q?pler=20loop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/bun.js/api/cron_parser.zig | 41 +++++++++------------------------- 1 file changed, 10 insertions(+), 31 deletions(-) diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index f59635d279d6..d1d62bdb5cd4 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -128,14 +128,11 @@ pub const CronExpression = struct { dt.minute += 1; dt.second = 0; - // dt.year only changes inside the date-normalize block (gated on - // date_dirty), but hour overflow forces date_dirty within ≤1440 - // iterations, so this check is reached and the loop is bounded. - var date_dirty = true; while (dt.year - start_year <= 8) { - // Carry hour/minute overflow explicitly so the candidate hour:minute - // is checked against the bitfields *before* DST shifts it (croner - // semantics: gap times fire shifted forward, same day). + // Carry hour/minute manually so the candidate {hour,minute} is + // checked against the bitfields *before* DST shifts it; normalize + // the date+weekday via a noon round-trip (DST at midday stays on + // the same calendar day, so only date fields are copied back). if (dt.minute > 59) { dt.minute -= 60; dt.hour += 1; @@ -143,55 +140,37 @@ pub const CronExpression = struct { if (dt.hour > 23) { dt.hour -= 24; dt.day += 1; - date_dirty = true; - } - // Normalize the date (year/month/day overflow + weekday) via a - // round-trip at noon. Any DST shift at midday stays within the same - // calendar day, so the date and weekday are still correct. Skip - // when only hour/minute moved. - if (date_dirty) { - const noon_ms = try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, 12, 0, 0, 0); - const n = globalObject.msToGregorianDateTime(noon_ms); - dt.year = n.year; - dt.month = n.month; - dt.day = n.day; - dt.weekday = n.weekday; - date_dirty = false; } + const n = globalObject.msToGregorianDateTime(try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, 12, 0, 0, 0)); + dt.year = n.year; + dt.month = n.month; + dt.day = n.day; + dt.weekday = n.weekday; - // Check month if (!bitSet(u16, self.months, @intCast(dt.month))) { dt.month += 1; dt.day = 1; dt.hour = 0; dt.minute = 0; - date_dirty = true; continue; } - if (!self.matchesDay(dt.day, dt.weekday)) { dt.day += 1; dt.hour = 0; dt.minute = 0; - date_dirty = true; continue; } - - // Check hour if (!bitSet(u32, self.hours, @intCast(dt.hour))) { dt.hour += 1; dt.minute = 0; continue; } - - // Check minute if (!bitSet(u64, self.minutes, @intCast(dt.minute))) { dt.minute += 1; continue; } - // All fields match - const result = try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0); + const result = try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, dt.hour, dt.minute, 0, 0); // During DST fall-back, gregorianDateTimeToMS picks the FORMER // occurrence of an ambiguous local time, and the wall-clock walk // above can step over the entire second occurrence. For wild From 9b4ab1129a5b81f1749f953edb82f3eaee751e1f Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 16:08:03 -0700 Subject: [PATCH 49/58] =?UTF-8?q?cron=5Fparser:=20extract=20resolveLocalMa?= =?UTF-8?q?tch=20=E2=80=94=20next()=20is=20now=20purely=20the=20wall-clock?= =?UTF-8?q?=20walk?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/bun.js/api/cron_parser.zig | 48 ++++++++++++++++------------------ 1 file changed, 22 insertions(+), 26 deletions(-) diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index d1d62bdb5cd4..82439693b428 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -114,19 +114,32 @@ pub const CronExpression = struct { self.matchesDay(t.day, t.weekday); } + /// Convert a matching wall-clock `dt` to a real instant strictly after + /// `from_ms`, handling DST. Returns null if no such instant exists for + /// this wall-clock minute (fall-back FORMER already passed and the + /// schedule is fixed-time, so it fires once — cronie semantics). + fn resolveLocalMatch(self: CronExpression, globalObject: *jsc.JSGlobalObject, dt: jsc.JSGlobalObject.GregorianDateTime, from_ms: f64) bun.JSError!?f64 { + const result = try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, dt.hour, dt.minute, 0, 0); + // During fall-back, `result` is the FORMER occurrence and the wall-clock + // walk steps over the second one. For schedules with `*` minute or `*` + // hour, scan real-time minutes (capped at the largest DST shift) for an + // earlier match in the repeated window. + if (self.minutes == all_minutes or self.hours == all_hours) { + var probe = (@floor(from_ms / minute_ms) + 1) * minute_ms; + const cap = @min(result, from_ms + (max_dst_shift_min + 1) * minute_ms); + while (probe < cap) : (probe += minute_ms) + if (self.matchesInstant(globalObject, probe)) return probe; + } + return if (result > from_ms) result else null; + } + /// Compute the next time (in ms since epoch) that matches this expression - /// in the system's local time zone, starting from `from_ms`. Returns null + /// in the system's local time zone, strictly after `from_ms`. Returns null /// if no match found within 8 years. pub fn next(self: CronExpression, globalObject: *jsc.JSGlobalObject, from_ms: f64) bun.JSError!?f64 { var dt = globalObject.msToGregorianDateTime(from_ms); const start_year = dt.year; - // cronie: schedules with `*` minute or `*` hour run through a fall-back - // repeated hour; fixed-time schedules fire once. We use the semantic - // check (all bits set) so `*/1` counts as wild — matches the npm camp. - const wild = self.minutes == all_minutes or self.hours == all_hours; - dt.minute += 1; - dt.second = 0; while (dt.year - start_year <= 8) { // Carry hour/minute manually so the candidate {hour,minute} is @@ -170,25 +183,8 @@ pub const CronExpression = struct { continue; } - const result = try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, dt.hour, dt.minute, 0, 0); - // During DST fall-back, gregorianDateTimeToMS picks the FORMER - // occurrence of an ambiguous local time, and the wall-clock walk - // above can step over the entire second occurrence. For wild - // schedules, scan real-time minutes between from_ms and result - // (capped at 2h, the largest real-world DST shift) for an earlier - // match in the repeated window. - if (wild and result > from_ms + minute_ms) { - var probe = (@floor(from_ms / minute_ms) + 1) * minute_ms; - const cap = @min(result, from_ms + (max_dst_shift_min + 1) * minute_ms); - while (probe < cap) : (probe += minute_ms) { - if (self.matchesInstant(globalObject, probe)) return probe; - } - } - if (result <= from_ms) { - dt.minute += 1; - continue; - } - return result; + if (try self.resolveLocalMatch(globalObject, dt, from_ms)) |r| return r; + dt.minute += 1; } return null; } From 3a61b3b10192f6d78691390b01c02451526d6286 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 16:11:53 -0700 Subject: [PATCH 50/58] cron: add Lord Howe 30-min fall-back tests + hourly chain tests through DST --- test/js/bun/cron/cron-local-time.test.ts | 45 ++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/test/js/bun/cron/cron-local-time.test.ts b/test/js/bun/cron/cron-local-time.test.ts index 4bab6596653a..33025168935e 100644 --- a/test/js/bun/cron/cron-local-time.test.ts +++ b/test/js/bun/cron/cron-local-time.test.ts @@ -120,6 +120,51 @@ describe.concurrent("Bun.cron.parse — DST transitions", () => { expect(next).toBe("2025-10-04T15:45:00.000Z"); }); + test("Lord Howe: 30-minute fall-back — wildcard fires through repeated half-hour", async () => { + // 2025-04-06 02:00 LHDT (+11) → 01:30 LHST (+10:30); 1:30-1:59 repeats. + // After first 1:59 (14:59Z), every-minute → second 1:30 (15:00Z). + const a = await parseInTZ("Australia/Lord_Howe", "* * * * *", "2025-04-05T14:59:01Z"); + expect(a).toBe("2025-04-05T15:00:00.000Z"); + // After first 1:45, "45 *" → second 1:45. + const b = await parseInTZ("Australia/Lord_Howe", "45 * * * *", "2025-04-05T14:45:01Z"); + expect(b).toBe("2025-04-05T15:15:00.000Z"); + }); + + test("Lord Howe: 30-minute fall-back — fixed-time fires once", async () => { + // After first 1:45, "45 1" (fixed) → next day, not the second 1:45. + const next = await parseInTZ("Australia/Lord_Howe", "45 1 * * *", "2025-04-05T14:45:01Z"); + expect(next).toBe("2025-04-06T15:15:00.000Z"); + }); + + test("fall-back: hourly chain walks 0→1→1→2 (both occurrences)", async () => { + let t = "2025-11-02T03:59:00Z"; + const seq: string[] = []; + for (let i = 0; i < 4; i++) { + t = await parseInTZ("America/New_York", "0 * * * *", t); + seq.push(t); + } + expect(seq).toEqual([ + "2025-11-02T04:00:00.000Z", // 0:00 EDT + "2025-11-02T05:00:00.000Z", // 1st 1:00 EDT + "2025-11-02T06:00:00.000Z", // 2nd 1:00 EST + "2025-11-02T07:00:00.000Z", // 2:00 EST + ]); + }); + + test("spring-forward: hourly chain walks 1→3→4 (no double-fire at 3)", async () => { + let t = "2025-03-09T05:59:00Z"; + const seq: string[] = []; + for (let i = 0; i < 3; i++) { + t = await parseInTZ("America/New_York", "0 * * * *", t); + seq.push(t); + } + expect(seq).toEqual([ + "2025-03-09T06:00:00.000Z", // 1:00 EST + "2025-03-09T07:00:00.000Z", // 3:00 EDT (2:00 doesn't exist) + "2025-03-09T08:00:00.000Z", // 4:00 EDT + ]); + }); + test("Santiago: midnight spring-forward gap shifts to 01:00 same day", async () => { // America/Santiago 2025-09-07 00:00→01:00. "0 0 * * *" → 01:00 CLST. const next = await parseInTZ("America/Santiago", "0 0 * * *", "2025-09-06T23:00:00-04:00"); From b9415aa560dd50555d4ad5a8b7664a4adf966514 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 16:28:27 -0700 Subject: [PATCH 51/58] cron: parse() and in-process callback are UTC; drop local-time/DST handling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bun.cron.parse() stays UTC (preserving existing behavior). The in-process Bun.cron(schedule, handler) follows parse() and is also UTC. The OS-level Bun.cron(path, schedule, title) remains local (crontab/launchd/schtasks are inherently local — set TZ=UTC to align both forms). UTC has no DST, so next() reverts to a simple round-trip walk. Removed: resolveLocalMatch, matchesInstant, matchesDay, the fall-back scan, the noon-normalize trick, and minute_ms/max_dst_shift_min constants. Kept: weekday-7 range fix, year-bound, error messages. cron-local-time.test.ts → cron-parse.test.ts (DST tests dropped, weekday-7 tests now in-process, added a TZ-ignored verification). --- docs/runtime/cron.mdx | 15 +- packages/bun-types/bun.d.ts | 15 +- src/bun.js/api/cron_parser.zig | 88 +++--------- src/bun.js/bindings/JSGlobalObject.zig | 7 - test/js/bun/cron/cron-local-time.test.ts | 173 ----------------------- test/js/bun/cron/cron-parse.test.ts | 71 ++++++++++ 6 files changed, 100 insertions(+), 269 deletions(-) delete mode 100644 test/js/bun/cron/cron-local-time.test.ts create mode 100644 test/js/bun/cron/cron-parse.test.ts diff --git a/docs/runtime/cron.mdx b/docs/runtime/cron.mdx index 5e8120d29dfc..409e7f0c6c6c 100644 --- a/docs/runtime/cron.mdx +++ b/docs/runtime/cron.mdx @@ -18,7 +18,7 @@ Bun.cron("0 * * * *", async () => { **Parse a cron expression to find the next matching time:** ```ts -// Next weekday at 9:30 AM local time +// Next weekday at 9:30 AM UTC const next = Bun.cron.parse("30 9 * * MON-FRI"); ``` @@ -32,7 +32,7 @@ await Bun.cron("./worker.ts", "30 2 * * MON", "weekly-report"); ## `Bun.cron.parse()` -Parse a cron expression and return the next matching `Date` in the system's local time zone. +Parse a cron expression and return the next matching `Date` in UTC. ```ts const next = Bun.cron.parse("*/15 * * * *"); @@ -113,19 +113,14 @@ Both `0` and `7` mean Sunday in the weekday field. ```ts const next = Bun.cron.parse("@daily"); -console.log(next); // => next local midnight +console.log(next); // => next UTC midnight ``` ### Time zone -Schedules are interpreted in the system's **local time zone** — the same way crontab, launchd, and Windows Task Scheduler read them. The OS-level form and the in-process callback form fire at the same wall-clock time. +`Bun.cron.parse()` and the in-process `Bun.cron(schedule, handler)` interpret schedules in **UTC**. There is no DST to handle — `0 9 * * *` always means 9:00 UTC. -To use UTC, set `TZ=UTC` in the environment. - -DST transitions: - -- **Spring-forward** — a schedule that lands in the missing hour fires that day, shifted forward by the gap (e.g. `30 2 * * *` runs at 3:30 on the spring-forward day). For multi-minute patterns inside the gap (`*/15 2 * * *`), only the first match fires. -- **Fall-back** — a fixed-time schedule in the duplicated hour (`30 1 * * *`) fires once, at the first occurrence. A schedule whose minute or hour field is `*` (`0 * * * *`, `* * * * *`) fires through **both** occurrences — once per real-time minute, matching crontab on Linux. +The OS-level `Bun.cron(path, schedule, title)` uses the **system's local time zone**, because that's how crontab, launchd, and Windows Task Scheduler work. To make the two forms agree, run the process with `TZ=UTC`. ### Day-of-month and day-of-week interaction diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index d347ffa7cac5..978343711693 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7438,7 +7438,8 @@ declare module "bun" { * * ### Cron expression syntax * - * Five fields: `minute hour day-of-month month day-of-week`. + * Five fields: `minute hour day-of-month month day-of-week`. Schedules are + * interpreted in **UTC** — `0 9 * * *` fires at 9:00 UTC, regardless of `TZ`. * * | Field | Values | Special chars | * |-------|--------|---------------| @@ -7592,9 +7593,7 @@ declare module "bun" { */ remove(title: string): Promise<void>; /** - * Parse a cron expression and return the next matching `Date` in the - * system's local time zone — the same way crontab, launchd, and Windows - * Task Scheduler interpret schedules. Set `TZ=UTC` to use UTC. + * Parse a cron expression and return the next matching `Date` in UTC. * * Supports the same syntax as {@link Bun.cron} — 5-field expressions, named * days/months, and predefined nicknames like `@daily`. @@ -7603,18 +7602,14 @@ declare module "bun" { * matching uses OR logic per [POSIX cron](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/crontab.html): * a date matches if **either** field matches. * - * DST: spring-forward times shift forward by the gap; in the fall-back - * duplicated hour, fixed-time schedules fire once (first occurrence) while - * schedules with `*` minute or hour fire through both occurrences. - * * @param expression - A cron expression or nickname (e.g. `"0,15,30,45 * * * *"`, `"0 9 * * MON-FRI"`, `"@hourly"`) * @param relativeDate - Starting point for the search (defaults to `Date.now()`). Accepts a `Date` or milliseconds since epoch. - * @returns The next `Date` matching the expression in local time, or `null` if no match exists within 8 years (e.g. `"0 0 30 2 *"` — Feb 30 never occurs) + * @returns The next `Date` matching the expression in UTC, or `null` if no match exists within 8 years (e.g. `"0 0 30 2 *"` — Feb 30 never occurs) * @throws If the expression is invalid or `relativeDate` is `NaN`/`Infinity` * * @example * ```ts - * // Next weekday at 09:30 local time + * // Next weekday at 09:30 UTC * const next = Bun.cron.parse("30 9 * * MON-FRI"); * * // Chain calls to get a sequence diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index 82439693b428..3aa4630c41a6 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -1,7 +1,7 @@ /// Cron expression parser and next-occurrence calculator. /// /// Parses standard 5-field cron expressions (minute hour day month weekday) -/// into a bitset representation, and computes the next matching local time. +/// into a bitset representation, and computes the next matching UTC time. /// /// Supports: /// - Wildcards: * @@ -94,71 +94,18 @@ pub const CronExpression = struct { return stream.getWritten(); } - /// POSIX cron: if both DOM and DOW are restricted (not `*`), match either; - /// otherwise match both (a `*` field matches all anyway). - fn matchesDay(self: CronExpression, day: i32, weekday: i32) bool { - const day_ok = bitSet(u32, self.days, @intCast(day)); - const weekday_ok = bitSet(u8, self.weekdays, @intCast(weekday)); - return if (!self.days_is_wildcard and !self.weekdays_is_wildcard) - day_ok or weekday_ok - else - day_ok and weekday_ok; - } - - /// Check if a real instant matches all five fields in local time. - fn matchesInstant(self: CronExpression, globalObject: *jsc.JSGlobalObject, ms: f64) bool { - const t = globalObject.msToGregorianDateTime(ms); - return bitSet(u64, self.minutes, @intCast(t.minute)) and - bitSet(u32, self.hours, @intCast(t.hour)) and - bitSet(u16, self.months, @intCast(t.month)) and - self.matchesDay(t.day, t.weekday); - } - - /// Convert a matching wall-clock `dt` to a real instant strictly after - /// `from_ms`, handling DST. Returns null if no such instant exists for - /// this wall-clock minute (fall-back FORMER already passed and the - /// schedule is fixed-time, so it fires once — cronie semantics). - fn resolveLocalMatch(self: CronExpression, globalObject: *jsc.JSGlobalObject, dt: jsc.JSGlobalObject.GregorianDateTime, from_ms: f64) bun.JSError!?f64 { - const result = try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, dt.hour, dt.minute, 0, 0); - // During fall-back, `result` is the FORMER occurrence and the wall-clock - // walk steps over the second one. For schedules with `*` minute or `*` - // hour, scan real-time minutes (capped at the largest DST shift) for an - // earlier match in the repeated window. - if (self.minutes == all_minutes or self.hours == all_hours) { - var probe = (@floor(from_ms / minute_ms) + 1) * minute_ms; - const cap = @min(result, from_ms + (max_dst_shift_min + 1) * minute_ms); - while (probe < cap) : (probe += minute_ms) - if (self.matchesInstant(globalObject, probe)) return probe; - } - return if (result > from_ms) result else null; - } - - /// Compute the next time (in ms since epoch) that matches this expression - /// in the system's local time zone, strictly after `from_ms`. Returns null - /// if no match found within 8 years. + /// Compute the next UTC time (in ms since epoch) that matches this + /// expression, strictly after `from_ms`. Returns null if no match found + /// within 8 years. pub fn next(self: CronExpression, globalObject: *jsc.JSGlobalObject, from_ms: f64) bun.JSError!?f64 { - var dt = globalObject.msToGregorianDateTime(from_ms); + var dt = globalObject.msToGregorianDateTimeUTC(from_ms); const start_year = dt.year; dt.minute += 1; + dt.second = 0; while (dt.year - start_year <= 8) { - // Carry hour/minute manually so the candidate {hour,minute} is - // checked against the bitfields *before* DST shifts it; normalize - // the date+weekday via a noon round-trip (DST at midday stays on - // the same calendar day, so only date fields are copied back). - if (dt.minute > 59) { - dt.minute -= 60; - dt.hour += 1; - } - if (dt.hour > 23) { - dt.hour -= 24; - dt.day += 1; - } - const n = globalObject.msToGregorianDateTime(try globalObject.gregorianDateTimeToMS(dt.year, dt.month, dt.day, 12, 0, 0, 0)); - dt.year = n.year; - dt.month = n.month; - dt.day = n.day; - dt.weekday = n.weekday; + // Normalize overflow + recompute weekday via a UTC round-trip. + dt = globalObject.msToGregorianDateTimeUTC(try globalObject.gregorianDateTimeToMSUTC(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0)); if (!bitSet(u16, self.months, @intCast(dt.month))) { dt.month += 1; @@ -167,7 +114,15 @@ pub const CronExpression = struct { dt.minute = 0; continue; } - if (!self.matchesDay(dt.day, dt.weekday)) { + // POSIX: if both DOM and DOW are restricted (not `*`), either + // matching is enough; otherwise the `*` field matches all anyway. + const day_ok = bitSet(u32, self.days, @intCast(dt.day)); + const weekday_ok = bitSet(u8, self.weekdays, @intCast(dt.weekday)); + const day_match = if (!self.days_is_wildcard and !self.weekdays_is_wildcard) + day_ok or weekday_ok + else + day_ok and weekday_ok; + if (!day_match) { dt.day += 1; dt.hour = 0; dt.minute = 0; @@ -183,8 +138,7 @@ pub const CronExpression = struct { continue; } - if (try self.resolveLocalMatch(globalObject, dt, from_ms)) |r| return r; - dt.minute += 1; + return try globalObject.gregorianDateTimeToMSUTC(dt.year, dt.month, dt.day, dt.hour, dt.minute, 0, 0); } return null; } @@ -194,11 +148,7 @@ pub const CronExpression = struct { // Name lookup tables // ============================================================================ -const minute_ms: f64 = 60_000; -const max_dst_shift_min: f64 = 120; - -pub const all_minutes: u64 = (1 << 60) - 1; -pub const all_hours: u32 = (1 << 24) - 1; +const all_hours: u32 = (1 << 24) - 1; pub const all_days: u32 = ((1 << 32) - 1) & ~@as(u32, 1); pub const all_months: u16 = ((1 << 13) - 1) & ~@as(u16, 1); pub const all_weekdays: u8 = (1 << 7) - 1; diff --git a/src/bun.js/bindings/JSGlobalObject.zig b/src/bun.js/bindings/JSGlobalObject.zig index 2e3d6cc1640a..bccbe3dd30ef 100644 --- a/src/bun.js/bindings/JSGlobalObject.zig +++ b/src/bun.js/bindings/JSGlobalObject.zig @@ -49,13 +49,6 @@ pub const JSGlobalObject = opaque { return dt; } - pub fn msToGregorianDateTime(this: *jsc.JSGlobalObject, ms: f64) GregorianDateTime { - jsc.markBinding(@src()); - var dt: GregorianDateTime = undefined; - bun.cpp.Bun__msToGregorianDateTime(this, ms, true, &dt.year, &dt.month, &dt.day, &dt.hour, &dt.minute, &dt.second, &dt.weekday); - return dt; - } - pub fn throwTODO(this: *JSGlobalObject, msg: []const u8) bun.JSError { const err = this.createErrorInstance("{s}", .{msg}); if (err == .zero) { diff --git a/test/js/bun/cron/cron-local-time.test.ts b/test/js/bun/cron/cron-local-time.test.ts deleted file mode 100644 index 33025168935e..000000000000 --- a/test/js/bun/cron/cron-local-time.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { bunEnv, bunExe } from "harness"; - -// Bun.cron.parse() and the in-process Bun.cron(schedule, handler) interpret -// cron expressions in the system's local time zone — matching the OS-level -// overload (crontab/launchd/schtasks all use local time). -// -// Each test spawns a subprocess with a fixed TZ so the assertions are -// independent of the host's zone. - -async function parseInTZ(tz: string, expr: string, fromISO: string): Promise<string> { - await using proc = Bun.spawn({ - cmd: [ - bunExe(), - "-e", - `process.stdout.write(Bun.cron.parse(${JSON.stringify(expr)}, new Date(${JSON.stringify(fromISO)})).toISOString())`, - ], - env: { ...bunEnv, TZ: tz }, - }); - const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); - expect(exitCode).toBe(0); - return stdout; -} - -describe.concurrent("Bun.cron.parse — local time zone", () => { - test("0 9 * * * in America/Los_Angeles is 9am Pacific (PDT = UTC-7)", async () => { - const next = await parseInTZ("America/Los_Angeles", "0 9 * * *", "2026-06-15T00:00:00Z"); - // 2026-06-15 00:00 UTC = 2026-06-14 17:00 PDT; next 9am PDT = 2026-06-15 09:00 PDT = 16:00 UTC - expect(next).toBe("2026-06-15T16:00:00.000Z"); - }); - - test("0 9 * * * in UTC is 9am UTC", async () => { - const next = await parseInTZ("UTC", "0 9 * * *", "2026-06-15T00:00:00Z"); - expect(next).toBe("2026-06-15T09:00:00.000Z"); - }); - - test("0 9 * * * in Asia/Tokyo is 9am JST (UTC+9, no DST)", async () => { - const next = await parseInTZ("Asia/Tokyo", "0 9 * * *", "2026-06-15T00:00:00Z"); - // 2026-06-15 00:00 UTC = 2026-06-15 09:00 JST → already at 09:00 but parse() returns the - // NEXT occurrence strictly after, so next is 2026-06-16 09:00 JST = 2026-06-16 00:00 UTC - expect(next).toBe("2026-06-16T00:00:00.000Z"); - }); - - test("weekday matching uses local day-of-week (0 12 * * MON across the dateline)", async () => { - // Pacific/Auckland is UTC+12 (NZST in June). 2026-06-15 is a Monday in NZST. - // 12:00 NZST = 00:00 UTC same date. - const next = await parseInTZ("Pacific/Auckland", "0 12 * * MON", "2026-06-14T23:00:00Z"); - // 2026-06-14 23:00 UTC = 2026-06-15 11:00 NZST (Mon); next Mon 12:00 NZST = 2026-06-15 00:00 UTC - expect(next).toBe("2026-06-15T00:00:00.000Z"); - }); -}); - -describe.concurrent("Bun.cron.parse — weekday 7 = Sunday in ranges", () => { - // 2026-01-01 is a Thursday. next() is strictly-after, so the first match for an - // every-day schedule is 2026-01-02. - test("1-7 means Mon-Sun (every day)", async () => { - expect(await parseInTZ("UTC", "0 0 * * 1-7", "2026-01-01T00:00:00Z")).toBe("2026-01-02T00:00:00.000Z"); - }); - test("5-7 means Fri-Sun", async () => { - expect(await parseInTZ("UTC", "0 0 * * 5-7", "2026-01-01T00:00:00Z")).toBe("2026-01-02T00:00:00.000Z"); - }); - test("6-7 means Sat-Sun", async () => { - expect(await parseInTZ("UTC", "0 0 * * 6-7", "2026-01-01T00:00:00Z")).toBe("2026-01-03T00:00:00.000Z"); - }); - test("0-7 means every day", async () => { - expect(await parseInTZ("UTC", "0 0 * * 0-7", "2026-01-01T00:00:00Z")).toBe("2026-01-02T00:00:00.000Z"); - }); - test("scalar 7 still means Sunday", async () => { - expect(await parseInTZ("UTC", "0 0 * * 7", "2026-01-01T00:00:00Z")).toBe("2026-01-04T00:00:00.000Z"); - }); -}); - -describe.concurrent("Bun.cron.parse — DST transitions", () => { - test("spring-forward: schedule in the missing hour fires shifted forward (same day)", async () => { - // US 2025 spring-forward: 2025-03-09 02:00 EST → 03:00 EDT (2:00-2:59 don't exist). - // "30 2 * * *" fires at 03:30 EDT — the gap-shifted instant. Matches croner and cron-parser. - const next = await parseInTZ("America/New_York", "30 2 * * *", "2025-03-09T05:00:00Z"); // = 00:00 EST - expect(next).toBe("2025-03-09T07:30:00.000Z"); // 03:30 EDT - }); - - test("fall-back: schedule in the duplicated hour fires at the first occurrence", async () => { - // US 2025 fall-back: 2025-11-02 02:00 EDT → 01:00 EST (1:00-1:59 occurs twice). - // Starting from 00:30 EDT (= 04:30 UTC), next "30 1 * * *" is the first 01:30 (EDT) = 05:30 UTC. - const next = await parseInTZ("America/New_York", "30 1 * * *", "2025-11-02T04:30:00Z"); - expect(next).toBe("2025-11-02T05:30:00.000Z"); - }); - - test("fall-back: starting from the second occurrence does not return a time before from", async () => { - // 06:30 UTC = 01:30 EST (the SECOND 01:30). next() must not return the first 01:30 (05:30 UTC). - const next = await parseInTZ("America/New_York", "30 1 * * *", "2025-11-02T06:30:00Z"); - // Next valid 01:30 is the following day (EST): 2025-11-03 01:30 EST = 06:30 UTC. - expect(next).toBe("2025-11-03T06:30:00.000Z"); - }); - - test("fall-back: wildcard hour fires through both occurrences (cronie semantics)", async () => { - // After the first 1:00 (05:00Z), next() returns the SECOND 1:00 (06:00Z). - // Matches cronie/Vixie and cron-parser. Fixed-time schedules (30 1 * * *) - // still fire once — only `*` minute or `*` hour schedules run through. - const next = await parseInTZ("America/New_York", "0 * * * *", "2025-11-02T05:00:01Z"); - expect(next).toBe("2025-11-02T06:00:00.000Z"); - }); - - test("fall-back: every-minute fires through both occurrences", async () => { - const next = await parseInTZ("America/New_York", "* * * * *", "2025-11-02T05:59:01Z"); - expect(next).toBe("2025-11-02T06:00:00.000Z"); - }); - - test("spring-forward: only the first match in the gap fires shifted (croner semantics)", async () => { - // "*/15 2 * * *" has 4 occurrences in the missing hour. Bun fires the first - // shifted to 3:00, then skips to next day. cron-parser shifts all four. - const first = await parseInTZ("America/New_York", "*/15 2 * * *", "2025-03-09T06:59:00Z"); - expect(first).toBe("2025-03-09T07:00:00.000Z"); // 03:00 EDT - const second = await parseInTZ("America/New_York", "*/15 2 * * *", "2025-03-09T07:00:00Z"); - expect(second).toBe("2025-03-10T06:00:00.000Z"); // next day 02:00 EDT - }); - - test("Lord Howe: 30-minute spring-forward gap shifts by 30 min", async () => { - // Australia/Lord_Howe 2025-10-05 02:00→02:30. "15 2 * * *" → 02:45 LHDT. - const next = await parseInTZ("Australia/Lord_Howe", "15 2 * * *", "2025-10-04T14:30:00Z"); - expect(next).toBe("2025-10-04T15:45:00.000Z"); - }); - - test("Lord Howe: 30-minute fall-back — wildcard fires through repeated half-hour", async () => { - // 2025-04-06 02:00 LHDT (+11) → 01:30 LHST (+10:30); 1:30-1:59 repeats. - // After first 1:59 (14:59Z), every-minute → second 1:30 (15:00Z). - const a = await parseInTZ("Australia/Lord_Howe", "* * * * *", "2025-04-05T14:59:01Z"); - expect(a).toBe("2025-04-05T15:00:00.000Z"); - // After first 1:45, "45 *" → second 1:45. - const b = await parseInTZ("Australia/Lord_Howe", "45 * * * *", "2025-04-05T14:45:01Z"); - expect(b).toBe("2025-04-05T15:15:00.000Z"); - }); - - test("Lord Howe: 30-minute fall-back — fixed-time fires once", async () => { - // After first 1:45, "45 1" (fixed) → next day, not the second 1:45. - const next = await parseInTZ("Australia/Lord_Howe", "45 1 * * *", "2025-04-05T14:45:01Z"); - expect(next).toBe("2025-04-06T15:15:00.000Z"); - }); - - test("fall-back: hourly chain walks 0→1→1→2 (both occurrences)", async () => { - let t = "2025-11-02T03:59:00Z"; - const seq: string[] = []; - for (let i = 0; i < 4; i++) { - t = await parseInTZ("America/New_York", "0 * * * *", t); - seq.push(t); - } - expect(seq).toEqual([ - "2025-11-02T04:00:00.000Z", // 0:00 EDT - "2025-11-02T05:00:00.000Z", // 1st 1:00 EDT - "2025-11-02T06:00:00.000Z", // 2nd 1:00 EST - "2025-11-02T07:00:00.000Z", // 2:00 EST - ]); - }); - - test("spring-forward: hourly chain walks 1→3→4 (no double-fire at 3)", async () => { - let t = "2025-03-09T05:59:00Z"; - const seq: string[] = []; - for (let i = 0; i < 3; i++) { - t = await parseInTZ("America/New_York", "0 * * * *", t); - seq.push(t); - } - expect(seq).toEqual([ - "2025-03-09T06:00:00.000Z", // 1:00 EST - "2025-03-09T07:00:00.000Z", // 3:00 EDT (2:00 doesn't exist) - "2025-03-09T08:00:00.000Z", // 4:00 EDT - ]); - }); - - test("Santiago: midnight spring-forward gap shifts to 01:00 same day", async () => { - // America/Santiago 2025-09-07 00:00→01:00. "0 0 * * *" → 01:00 CLST. - const next = await parseInTZ("America/Santiago", "0 0 * * *", "2025-09-06T23:00:00-04:00"); - expect(next).toBe("2025-09-07T04:00:00.000Z"); - }); -}); diff --git a/test/js/bun/cron/cron-parse.test.ts b/test/js/bun/cron/cron-parse.test.ts new file mode 100644 index 000000000000..939d0682b4f5 --- /dev/null +++ b/test/js/bun/cron/cron-parse.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, test } from "bun:test"; +import { bunEnv, bunExe } from "harness"; + +// Bun.cron.parse() and the in-process Bun.cron(schedule, handler) interpret +// schedules in UTC. The OS-level Bun.cron(path, schedule, title) overload +// uses the system's local time zone (crontab/launchd/schtasks all do). + +const parse = (expr: string, from: string) => Bun.cron.parse(expr, new Date(from))!.toISOString(); + +describe("Bun.cron.parse — UTC", () => { + test("0 9 * * * is 9am UTC regardless of process TZ", async () => { + // Parse is UTC; spawning under a non-UTC TZ should produce the same result. + for (const tz of ["America/Los_Angeles", "Asia/Tokyo", "UTC"]) { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + `process.stdout.write(Bun.cron.parse("0 9 * * *", new Date("2026-06-15T00:00:00Z")).toISOString())`, + ], + env: { ...bunEnv, TZ: tz }, + }); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + expect(stdout).toBe("2026-06-15T09:00:00.000Z"); + expect(exitCode).toBe(0); + } + }); + + test("weekday matching uses UTC day-of-week", () => { + // 2026-06-15 is a Monday in UTC. + expect(parse("0 12 * * MON", "2026-06-14T23:00:00Z")).toBe("2026-06-15T12:00:00.000Z"); + }); + + test("strictly-after: from = exact match returns the next occurrence", () => { + expect(parse("0 9 * * *", "2026-06-15T09:00:00Z")).toBe("2026-06-16T09:00:00.000Z"); + }); + + test("Feb 29 finds next leap year", () => { + expect(parse("0 0 29 2 *", "2026-01-01T00:00:00Z")).toBe("2028-02-29T00:00:00.000Z"); + }); + + test("impossible day/month (Feb 30) returns null quickly", () => { + const t = performance.now(); + expect(Bun.cron.parse("0 0 30 2 *", new Date("2026-01-01T00:00:00Z"))).toBeNull(); + expect(performance.now() - t).toBeLessThan(50); + }); + + test("DOM/DOW OR semantics when both restricted", () => { + // 0 0 13 * 5 → every 13th OR every Friday. From 2026-01-01 (Thu), first is Fri Jan 2. + expect(parse("0 0 13 * 5", "2026-01-01T00:00:00Z")).toBe("2026-01-02T00:00:00.000Z"); + }); +}); + +describe("Bun.cron.parse — weekday 7 = Sunday in ranges", () => { + // 2026-01-01 is a Thursday. next() is strictly-after, so the first match for + // an every-day schedule is 2026-01-02. + test("1-7 means Mon-Sun (every day)", () => { + expect(parse("0 0 * * 1-7", "2026-01-01T00:00:00Z")).toBe("2026-01-02T00:00:00.000Z"); + }); + test("5-7 means Fri-Sun", () => { + expect(parse("0 0 * * 5-7", "2026-01-01T00:00:00Z")).toBe("2026-01-02T00:00:00.000Z"); + }); + test("6-7 means Sat-Sun", () => { + expect(parse("0 0 * * 6-7", "2026-01-01T00:00:00Z")).toBe("2026-01-03T00:00:00.000Z"); + }); + test("0-7 means every day", () => { + expect(parse("0 0 * * 0-7", "2026-01-01T00:00:00Z")).toBe("2026-01-02T00:00:00.000Z"); + }); + test("scalar 7 still means Sunday", () => { + expect(parse("0 0 * * 7", "2026-01-01T00:00:00Z")).toBe("2026-01-04T00:00:00.000Z"); + }); +}); From 61b1f2407fcd6bd60e9b1d7b5da4f54dda153863 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 16:50:10 -0700 Subject: [PATCH 52/58] cron: remove dead raw_schedule field --- src/bun.js/api/cron.zig | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 89edecbf12b6..925302067233 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -55,7 +55,6 @@ pub const CronRegisterJob = struct { bun_exe: [:0]const u8, abs_path: [:0]const u8, schedule: [:0]const u8, // normalized numeric form for crontab/launchd - raw_schedule: [:0]const u8, // original form for --cron-period and schtasks parsing title: [:0]const u8, parsed_cron: CronExpression, @@ -191,7 +190,6 @@ pub const CronRegisterJob = struct { if (this.err_msg) |msg| bun.default_allocator.free(msg); bun.default_allocator.free(this.abs_path); bun.default_allocator.free(this.schedule); - bun.default_allocator.free(this.raw_schedule); bun.default_allocator.free(this.title); bun.default_allocator.destroy(this); } @@ -477,7 +475,6 @@ pub const CronRegisterJob = struct { .bun_exe = bun_exe, .abs_path = abs_path, .schedule = bun.handleOom(bun.default_allocator.dupeZ(u8, normalized_schedule)), - .raw_schedule = bun.handleOom(bun.default_allocator.dupeZ(u8, schedule_slice.slice())), .title = bun.handleOom(bun.default_allocator.dupeZ(u8, title_slice.slice())), .parsed_cron = parsed, .promise = jsc.JSPromise.Strong.init(globalObject), From 3ed45d0e5e96836fe4a01bde2709e334cf7ab68c Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 17:23:19 -0700 Subject: [PATCH 53/58] cron: skip cron_jobs list ref+append when not --hot and not a worker --- src/bun.js/api/cron.zig | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 925302067233..4b8ae70c2171 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -1065,8 +1065,13 @@ pub const CronJob = struct { return globalObject.throwInvalidArguments("Cron expression '{s}' has no future occurrences", .{schedule_slice.slice()}); }; - job.ref(); // owned by cron_jobs entry - bun.handleOom(vm.rareData().cron_jobs.append(bun.default_allocator, job)); + // The cron_jobs list exists so --hot reload and worker teardown can + // stop/release jobs. Main-thread VMs without --hot never enumerate it, + // so skip the list ref + append entirely. + if (vm.hot_reload == .hot or vm.worker != null) { + job.ref(); // owned by cron_jobs entry + bun.handleOom(vm.rareData().cron_jobs.append(bun.default_allocator, job)); + } const js_value = job.toJS(globalObject); job.this_value.setStrong(js_value, globalObject); From 892a093eda41295b61bb2aaa4aae56ed9a9a7453 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 17:39:11 -0700 Subject: [PATCH 54/58] cron: drop stale TZ-pinning in cron.test.ts; remove duplicate "may" in month_map --- src/bun.js/api/cron_parser.zig | 16 ++++++++-------- test/js/bun/cron/cron.test.ts | 7 ------- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/src/bun.js/api/cron_parser.zig b/src/bun.js/api/cron_parser.zig index 3aa4630c41a6..9da36f5df952 100644 --- a/src/bun.js/api/cron_parser.zig +++ b/src/bun.js/api/cron_parser.zig @@ -177,14 +177,14 @@ const weekday_map = bun.ComptimeStringMap(u7, .{ }); const month_map = bun.ComptimeStringMap(u7, .{ - .{ "jan", 1 }, .{ "feb", 2 }, .{ "mar", 3 }, - .{ "apr", 4 }, .{ "may", 5 }, .{ "jun", 6 }, - .{ "jul", 7 }, .{ "aug", 8 }, .{ "sep", 9 }, - .{ "oct", 10 }, .{ "nov", 11 }, .{ "dec", 12 }, - .{ "january", 1 }, .{ "february", 2 }, .{ "march", 3 }, - .{ "april", 4 }, .{ "may", 5 }, .{ "june", 6 }, - .{ "july", 7 }, .{ "august", 8 }, .{ "september", 9 }, - .{ "october", 10 }, .{ "november", 11 }, .{ "december", 12 }, + .{ "jan", 1 }, .{ "feb", 2 }, .{ "mar", 3 }, + .{ "apr", 4 }, .{ "may", 5 }, .{ "jun", 6 }, + .{ "jul", 7 }, .{ "aug", 8 }, .{ "sep", 9 }, + .{ "oct", 10 }, .{ "nov", 11 }, .{ "dec", 12 }, + .{ "january", 1 }, .{ "february", 2 }, .{ "march", 3 }, + .{ "april", 4 }, .{ "june", 6 }, .{ "july", 7 }, + .{ "august", 8 }, .{ "september", 9 }, .{ "october", 10 }, + .{ "november", 11 }, .{ "december", 12 }, }); // ============================================================================ diff --git a/test/js/bun/cron/cron.test.ts b/test/js/bun/cron/cron.test.ts index 21216a0176ab..2e0e3b5f1c8b 100644 --- a/test/js/bun/cron/cron.test.ts +++ b/test/js/bun/cron/cron.test.ts @@ -1405,13 +1405,6 @@ function nextN(expr: string, from: number, n: number): number[] { } describe("Bun.cron.parse", () => { - // parse() now interprets expressions in local time. These tests were written - // with Date.UTC inputs/expectations, so pin to UTC for this block. Local-time - // behavior is covered in cron-local-time.test.ts. - const savedTZ = process.env.TZ; - beforeAll(() => void (process.env.TZ = "UTC")); - afterAll(() => void (savedTZ === undefined ? delete process.env.TZ : (process.env.TZ = savedTZ))); - test("is a function that returns a Date", () => { expect(typeof Bun.cron.parse).toBe("function"); const result = Bun.cron.parse("* * * * *", Date.UTC(2025, 0, 15, 10, 30, 0)); From 2b384d5bd9ac11852bdd4f2611d25353f88b9ee2 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Fri, 3 Apr 2026 00:41:00 +0000 Subject: [PATCH 55/58] [autofix.ci] apply automated fixes --- test/js/bun/cron/cron.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/js/bun/cron/cron.test.ts b/test/js/bun/cron/cron.test.ts index 2e0e3b5f1c8b..bf24eab225ea 100644 --- a/test/js/bun/cron/cron.test.ts +++ b/test/js/bun/cron/cron.test.ts @@ -1,4 +1,4 @@ -import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { describe, expect, test } from "bun:test"; import { bunEnv, bunExe, isLinux, isMacOS, isWindows, tempDir } from "harness"; import { existsSync, readFileSync, unlinkSync, watch, writeFileSync } from "node:fs"; import { basename } from "node:path"; From cb9abd13eda3a93a6853b6ba782adc0822a5f2c8 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Thu, 2 Apr 2026 17:43:56 -0700 Subject: [PATCH 56/58] cron: validate bun_exe path for ' and % before crontab embed --- src/bun.js/api/cron.zig | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/bun.js/api/cron.zig b/src/bun.js/api/cron.zig index 4b8ae70c2171..57d47b24908c 100644 --- a/src/bun.js/api/cron.zig +++ b/src/bun.js/api/cron.zig @@ -469,6 +469,10 @@ pub const CronRegisterJob = struct { bun.default_allocator.free(abs_path); return globalObject.throw("Failed to get bun executable path", .{}); }; + if (bun.strings.indexOfAny(bun_exe, "'%") != null) { + bun.default_allocator.free(abs_path); + return globalObject.throwInvalidArguments("Bun executable path '{s}' contains characters (' or %) that cannot be safely embedded in a crontab entry", .{bun_exe}); + } const job = bun.handleOom(bun.default_allocator.create(CronRegisterJob)); job.* = .{ .global = globalObject, From a9b5e5ad6e5ee8406c1329cee63906d0c3f6e519 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Fri, 3 Apr 2026 11:26:43 -0700 Subject: [PATCH 57/58] Revert PipeReader.zig deinit reorder; fail-fast --hot test polls; bump worker test timeout MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The WindowsBufferedReader.deinit reorder (3e0005ebb6) broke Windows lifecycle scripts — callers that close via their own onReaderDone path then call deinit() relied on the source being nulled first so closeImpl no-ops. Reverting to original ordering. The cron stderr buffer is still freed by deinit(); the Pipe struct leak on spawn-failure is pre-existing. --hot test: race marker polls against proc.exitCode so a subprocess crash surfaces immediately instead of timing out. worker test: 70s→130s (ASAN startup can push past first minute boundary). --- src/io/PipeReader.zig | 4 ++-- test/js/bun/cron/in-process-cron.test.ts | 13 ++++++++++--- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/io/PipeReader.zig b/src/io/PipeReader.zig index 2f3586e56ed4..ce81e72d79d0 100644 --- a/src/io/PipeReader.zig +++ b/src/io/PipeReader.zig @@ -937,11 +937,11 @@ pub const WindowsBufferedReader = struct { MaxBuf.removeFromPipereader(&this.maxbuf); this.buffer().deinit(); const source = this.source orelse return; + this.source = null; if (!source.isClosed()) { - // closeImpl reads this.source; null it after. + // closeImpl will take care of freeing the source this.closeImpl(false); } - this.source = null; } pub fn setRawMode(this: *WindowsBufferedReader, value: bool) bun.sys.Maybe(void) { diff --git a/test/js/bun/cron/in-process-cron.test.ts b/test/js/bun/cron/in-process-cron.test.ts index 06cc7e8c1a51..e5e5f74f9f3c 100644 --- a/test/js/bun/cron/in-process-cron.test.ts +++ b/test/js/bun/cron/in-process-cron.test.ts @@ -252,7 +252,7 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { const [stdout, _stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); expect(stdout.trim()).toBe("ok"); expect(exitCode).toBe(0); - }, 70_000); + }, 130_000); test("sync throw in callback emits uncaughtException", async () => { // Matches setTimeout: sync throw → uncaughtException. Process exits 1 without a handler. @@ -374,8 +374,15 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { stderr: "pipe", }); const stderrP = proc.stderr.text(); + const waitFor = async (file: string) => { + while (!(await Bun.file(m(file)).exists())) { + if (proc.exitCode !== null) + throw new Error(`subprocess exited ${proc.exitCode} before ${file}: ${await stderrP}`); + await Bun.sleep(10); + } + }; - while (!(await Bun.file(m("v1.evaluated")).exists())) await Bun.sleep(10); + await waitFor("v1.evaluated"); // Delete the ghost cron; replace with a sentinel that fires on the same // boundary. When the sentinel fires, ghost.fired must NOT exist. @@ -392,7 +399,7 @@ describe.concurrent("Bun.cron (in-process) — firing", () => { `, ); - while (!(await Bun.file(m("v2.evaluated")).exists())) await Bun.sleep(10); + await waitFor("v2.evaluated"); const [exitCode, stderr] = await Promise.all([proc.exited, stderrP]); if (exitCode !== 0) console.error(stderr); From e5a57b855e273e48b167cc92418eda899aa5a521 Mon Sep 17 00:00:00 2001 From: Alistair Smith <hi@alistair.sh> Date: Fri, 3 Apr 2026 11:59:02 -0700 Subject: [PATCH 58/58] cron.test.ts: poll for marker instead of fs.watch(/tmp) (macOS symlink unreliable) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pre-existing flake on main: fs.watch("/tmp") misses events through the /tmp → /private/tmp symlink. The marker is written ~100ms after kickstart; the single existsSync fallback raced it. Poll loop is simpler and reliable. --- test/js/bun/cron/cron.test.ts | 25 ++++--------------------- 1 file changed, 4 insertions(+), 21 deletions(-) diff --git a/test/js/bun/cron/cron.test.ts b/test/js/bun/cron/cron.test.ts index bf24eab225ea..6bcbe747773b 100644 --- a/test/js/bun/cron/cron.test.ts +++ b/test/js/bun/cron/cron.test.ts @@ -1,7 +1,6 @@ import { describe, expect, test } from "bun:test"; import { bunEnv, bunExe, isLinux, isMacOS, isWindows, tempDir } from "harness"; -import { existsSync, readFileSync, unlinkSync, watch, writeFileSync } from "node:fs"; -import { basename } from "node:path"; +import { existsSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"; const crontabPath = Bun.which("crontab"); const hasCrontab = !!crontabPath && isLinux; @@ -1172,25 +1171,9 @@ describe.skipIf(!hasLaunchctl)("cron end-to-end (macOS)", () => { cmd: ["/bin/launchctl", "kickstart", `gui/${process.getuid!()}/bun.cron.test-mac-e2e`], }); - // Wait for the marker file to appear - const { promise, resolve, reject } = Promise.withResolvers<void>(); - const timer = setTimeout(() => { - watcher.close(); - reject(new Error("Timed out")); - }, 10000); - const watcher = watch("/tmp", (_, f) => { - if (f === basename(markerPath)) { - watcher.close(); - clearTimeout(timer); - resolve(); - } - }); - if (existsSync(markerPath)) { - watcher.close(); - clearTimeout(timer); - resolve(); - } - await promise; + // Wait for the marker file to appear. fs.watch("/tmp") on macOS is + // unreliable through the /tmp → /private/tmp symlink, so poll. + while (!existsSync(markerPath)) await Bun.sleep(10); const output = JSON.parse(readFileSync(markerPath, "utf8")); const after = Date.now();