From b572abfcb3fadbfdd3ce671a27463d67bcb77534 Mon Sep 17 00:00:00 2001 From: Igor Zinkovsky Date: Thu, 16 Nov 2023 14:19:00 -0800 Subject: feat(ext/cron) modify Deno.cron API to make handler arg last (#21225) This PR changes the `Deno.cron` API: * Marks the existing function as deprecated * Introduces 2 new overloads, where the handler arg is always last: ```ts Deno.cron( name: string, schedule: string, handler: () => Promise | void, ) Deno.cron( name: string, schedule: string, options?: { backoffSchedule?: number[]; signal?: AbortSignal }, handler: () => Promise | void, ) ``` This PR also fixes a bug, when other crons continue execution after one of the crons was closed using `signal`. --- ext/cron/01_cron.ts | 23 ++++++++++++++++++++--- ext/cron/local.rs | 7 +++++-- 2 files changed, 25 insertions(+), 5 deletions(-) (limited to 'ext/cron') diff --git a/ext/cron/01_cron.ts b/ext/cron/01_cron.ts index a615ae34b..30343905c 100644 --- a/ext/cron/01_cron.ts +++ b/ext/cron/01_cron.ts @@ -6,8 +6,12 @@ const core = Deno.core; function cron( name: string, schedule: string, - handler: () => Promise | void, - options?: { backoffSchedule?: number[]; signal?: AbortSignal }, + handlerOrOptions1: + | (() => Promise | void) + | ({ backoffSchedule?: number[]; signal?: AbortSignal }), + handlerOrOptions2?: + | (() => Promise | void) + | ({ backoffSchedule?: number[]; signal?: AbortSignal }), ) { if (name === undefined) { throw new TypeError("Deno.cron requires a unique name"); @@ -15,7 +19,20 @@ function cron( if (schedule === undefined) { throw new TypeError("Deno.cron requires a valid schedule"); } - if (handler === undefined) { + + let handler: () => Promise | void; + let options: { backoffSchedule?: number[]; signal?: AbortSignal } | undefined; + + if (typeof handlerOrOptions1 === "function") { + handler = handlerOrOptions1; + if (typeof handlerOrOptions2 === "function") { + throw new TypeError("options must be an object"); + } + options = handlerOrOptions2; + } else if (typeof handlerOrOptions2 === "function") { + handler = handlerOrOptions2; + options = handlerOrOptions1; + } else { throw new TypeError("Deno.cron requires a handler"); } diff --git a/ext/cron/local.rs b/ext/cron/local.rs index 0b6dcae2e..5f1ace6d1 100644 --- a/ext/cron/local.rs +++ b/ext/cron/local.rs @@ -174,8 +174,11 @@ impl RuntimeState { .map(move |name| (*ts, name.clone())) .collect::>() }) - .map(|(_, name)| { - (name.clone(), self.crons.get(&name).unwrap().next_tx.clone()) + .filter_map(|(_, name)| { + self + .crons + .get(&name) + .map(|c| (name.clone(), c.next_tx.clone())) }) .collect::>() }; -- cgit v1.2.3