From 46b91eceb15c3941bf1f8f62b98026ad3fde3e9f Mon Sep 17 00:00:00 2001 From: Igor Zinkovsky Date: Tue, 23 Jan 2024 16:45:11 -0800 Subject: [PATCH] fix(ext/cron): automatically override unspecified values (#22042) Fixes #22041 --- cli/tests/unit/cron_test.ts | 67 +++++++++++++++++++++++++++++++++++++ ext/cron/01_cron.ts | 21 +++++++++++- 2 files changed, 87 insertions(+), 1 deletion(-) diff --git a/cli/tests/unit/cron_test.ts b/cli/tests/unit/cron_test.ts index ed4500624e..02573a898d 100644 --- a/cli/tests/unit/cron_test.ts +++ b/cli/tests/unit/cron_test.ts @@ -391,3 +391,70 @@ Deno.test("error on two handlers", () => { "Deno.cron requires a single handler", ); }); + +Deno.test("Parse test", () => { + assertEquals( + parseScheduleToString({ + minute: 3, + }), + "3 * * * *", + ); + assertEquals( + parseScheduleToString({ + hour: { every: 2 }, + }), + "0 */2 * * *", + ); + assertEquals( + parseScheduleToString({ + dayOfMonth: { every: 10 }, + }), + "0 0 */10 * *", + ); + assertEquals( + parseScheduleToString({ + month: { every: 3 }, + }), + "0 0 1 */3 *", + ); + assertEquals( + parseScheduleToString({ + dayOfWeek: { every: 2 }, + }), + "0 0 * * */2", + ); + assertEquals( + parseScheduleToString({ + minute: 3, + hour: { every: 2 }, + }), + "3 */2 * * *", + ); + assertEquals( + parseScheduleToString({ + dayOfMonth: { start: 1, end: 10 }, + }), + "0 0 1-10 * *", + ); + assertEquals( + parseScheduleToString({ + minute: { every: 10 }, + dayOfMonth: { every: 5 }, + }), + "*/10 * */5 * *", + ); + assertEquals( + parseScheduleToString({ + hour: { every: 3 }, + month: { every: 2 }, + }), + "0 */3 * */2 *", + ); + assertEquals( + parseScheduleToString({ + minute: { every: 5 }, + month: { every: 2 }, + }), + "*/5 * * */2 *", + ); +}); diff --git a/ext/cron/01_cron.ts b/ext/cron/01_cron.ts index 84e5c7fff8..c2a0c9cd13 100644 --- a/ext/cron/01_cron.ts +++ b/ext/cron/01_cron.ts @@ -62,7 +62,7 @@ export function parseScheduleToString( if (typeof schedule === "string") { return schedule; } else { - const { + let { minute, hour, dayOfMonth, @@ -70,6 +70,25 @@ export function parseScheduleToString( dayOfWeek, } = schedule; + // Automatically override unspecified values for convenience. For example, + // to run every 2 hours, `{ hour: { every: 2 } }` can be specified without + // explicitely specifying `minute`. + if (minute !== undefined) { + // Nothing to override. + } else if (hour !== undefined) { + // Override minute to 0 since it's not specified. + minute = 0; + } else if (dayOfMonth !== undefined || dayOfWeek !== undefined) { + // Override minute and hour to 0 since they're not specified. + minute = 0; + hour = 0; + } else if (month !== undefined) { + // Override minute and hour to 0, and dayOfMonth to 1 since they're not specified. + minute = 0; + hour = 0; + dayOfMonth = 1; + } + return formatToCronSchedule(minute) + " " + formatToCronSchedule(hour) + " " + formatToCronSchedule(dayOfMonth) +