summaryrefslogtreecommitdiff
path: root/ext/cron/01_cron.ts
diff options
context:
space:
mode:
authorRaashid Anwar <raashid12anwar@gmail.com>2023-12-01 03:21:56 +0530
committerGitHub <noreply@github.com>2023-11-30 13:51:56 -0800
commitab755a07d8997a1d41b84e91ca772815c9ef9699 (patch)
tree62361900a2f6de3d1a459c28be785d5c3f8990e2 /ext/cron/01_cron.ts
parent8050cbf39e69c1056eaa95e9e7b0887e50776b40 (diff)
feat(cron): added the support for json type schedule to cron api (#21340)
Added the support for JSON type schedule to cron API; previously it was string only. fixes #21122
Diffstat (limited to 'ext/cron/01_cron.ts')
-rw-r--r--ext/cron/01_cron.ts68
1 files changed, 67 insertions, 1 deletions
diff --git a/ext/cron/01_cron.ts b/ext/cron/01_cron.ts
index 30343905c..4a5250618 100644
--- a/ext/cron/01_cron.ts
+++ b/ext/cron/01_cron.ts
@@ -3,9 +3,73 @@
// @ts-ignore internal api
const core = Deno.core;
+export function formatToCronSchedule(
+ value?: number | { exact: number | number[] } | {
+ start?: number;
+ end?: number;
+ every?: number;
+ },
+): string {
+ if (value === undefined) {
+ return "*";
+ } else if (typeof value === "number") {
+ return value.toString();
+ } else {
+ const { exact } = value as { exact: number | number[] };
+ if (exact === undefined) {
+ const { start, end, every } = value as {
+ start?: number;
+ end?: number;
+ every?: number;
+ };
+ if (start !== undefined && end !== undefined && every !== undefined) {
+ return start + "-" + end + "/" + every;
+ } else if (start !== undefined && end !== undefined) {
+ return start + "-" + end;
+ } else if (start !== undefined && every !== undefined) {
+ return start + "/" + every;
+ } else if (start !== undefined) {
+ return start + "/1";
+ } else if (end === undefined && every !== undefined) {
+ return "*/" + every;
+ } else {
+ throw new TypeError("Invalid cron schedule");
+ }
+ } else {
+ if (typeof exact === "number") {
+ return exact.toString();
+ } else {
+ return exact.join(",");
+ }
+ }
+ }
+}
+
+export function parseScheduleToString(
+ schedule: string | Deno.CronSchedule,
+): string {
+ if (typeof schedule === "string") {
+ return schedule;
+ } else {
+ const {
+ minute,
+ hour,
+ dayOfMonth,
+ month,
+ dayOfWeek,
+ } = schedule;
+
+ return formatToCronSchedule(minute) +
+ " " + formatToCronSchedule(hour) +
+ " " + formatToCronSchedule(dayOfMonth) +
+ " " + formatToCronSchedule(month) +
+ " " + formatToCronSchedule(dayOfWeek);
+ }
+}
+
function cron(
name: string,
- schedule: string,
+ schedule: string | Deno.CronSchedule,
handlerOrOptions1:
| (() => Promise<void> | void)
| ({ backoffSchedule?: number[]; signal?: AbortSignal }),
@@ -20,6 +84,8 @@ function cron(
throw new TypeError("Deno.cron requires a valid schedule");
}
+ schedule = parseScheduleToString(schedule);
+
let handler: () => Promise<void> | void;
let options: { backoffSchedule?: number[]; signal?: AbortSignal } | undefined;