@warlock.js/scheduler 4.0.171 → 4.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -1
- package/cjs/index.cjs +1132 -0
- package/cjs/index.cjs.map +1 -0
- package/esm/cron-parser.d.mts +129 -0
- package/esm/cron-parser.d.mts.map +1 -0
- package/esm/cron-parser.mjs +210 -0
- package/esm/cron-parser.mjs.map +1 -0
- package/esm/index.d.mts +5 -0
- package/esm/index.mjs +5 -0
- package/esm/job.d.mts +386 -0
- package/esm/job.d.mts.map +1 -0
- package/esm/job.mjs +633 -0
- package/esm/job.mjs.map +1 -0
- package/esm/scheduler.d.mts +193 -0
- package/esm/scheduler.d.mts.map +1 -0
- package/esm/scheduler.mjs +261 -0
- package/esm/scheduler.mjs.map +1 -0
- package/esm/types.d.mts +70 -0
- package/esm/types.d.mts.map +1 -0
- package/llms-full.txt +888 -0
- package/llms.txt +15 -0
- package/package.json +40 -28
- package/skills/configure-retry-and-overlap/SKILL.md +137 -0
- package/skills/observe-scheduler/SKILL.md +153 -0
- package/skills/overview/SKILL.md +92 -0
- package/skills/pin-schedule-timezone/SKILL.md +114 -0
- package/skills/schedule-fluently/SKILL.md +141 -0
- package/skills/schedule-with-cron/SKILL.md +123 -0
- package/skills/scheduler-basics/SKILL.md +94 -0
- package/cjs/cron-parser.d.ts +0 -98
- package/cjs/cron-parser.d.ts.map +0 -1
- package/cjs/cron-parser.js +0 -193
- package/cjs/cron-parser.js.map +0 -1
- package/cjs/index.d.ts +0 -44
- package/cjs/index.d.ts.map +0 -1
- package/cjs/index.js +0 -1
- package/cjs/index.js.map +0 -1
- package/cjs/job.d.ts +0 -332
- package/cjs/job.d.ts.map +0 -1
- package/cjs/job.js +0 -616
- package/cjs/job.js.map +0 -1
- package/cjs/scheduler.d.ts +0 -182
- package/cjs/scheduler.d.ts.map +0 -1
- package/cjs/scheduler.js +0 -316
- package/cjs/scheduler.js.map +0 -1
- package/cjs/types.d.ts +0 -63
- package/cjs/types.d.ts.map +0 -1
- package/cjs/utils.d.ts +0 -3
- package/cjs/utils.d.ts.map +0 -1
- package/esm/cron-parser.d.ts +0 -98
- package/esm/cron-parser.d.ts.map +0 -1
- package/esm/cron-parser.js +0 -193
- package/esm/cron-parser.js.map +0 -1
- package/esm/index.d.ts +0 -44
- package/esm/index.d.ts.map +0 -1
- package/esm/index.js +0 -1
- package/esm/index.js.map +0 -1
- package/esm/job.d.ts +0 -332
- package/esm/job.d.ts.map +0 -1
- package/esm/job.js +0 -616
- package/esm/job.js.map +0 -1
- package/esm/scheduler.d.ts +0 -182
- package/esm/scheduler.d.ts.map +0 -1
- package/esm/scheduler.js +0 -316
- package/esm/scheduler.js.map +0 -1
- package/esm/types.d.ts +0 -63
- package/esm/types.d.ts.map +0 -1
- package/esm/utils.d.ts +0 -3
- package/esm/utils.d.ts.map +0 -1
package/esm/job.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"job.mjs","names":[],"sources":["../../../../../@warlock.js/scheduler/src/job.ts"],"sourcesContent":["import dayjs, { type Dayjs } from \"dayjs\";\nimport isSameOrAfter from \"dayjs/plugin/isSameOrAfter.js\";\nimport timezone from \"dayjs/plugin/timezone.js\";\nimport utc from \"dayjs/plugin/utc.js\";\nimport { CronParser } from \"./cron-parser\";\nimport type { Day, JobIntervals, JobResult, RetryConfig, TimeType } from \"./types\";\n\ndayjs.extend(utc);\ndayjs.extend(timezone);\ndayjs.extend(isSameOrAfter);\n\nexport type JobCallback = (job: Job) => Promise<any>;\n\n/**\n * Days of week mapping (lowercase for consistency with Day type)\n */\nconst DAYS_OF_WEEK: Day[] = [\n \"sunday\",\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n];\n\n/**\n * Validate a `HH:mm` or `HH:mm:ss` string and return its parts.\n * Throws when the format is malformed or any part is out of range.\n */\nfunction parseTimeString(time: string): {\n hour: number;\n minute: number;\n second: number;\n} {\n if (!/^\\d{1,2}:\\d{2}(:\\d{2})?$/.test(time)) {\n throw new Error(\"Invalid time format. Use HH:mm or HH:mm:ss.\");\n }\n\n const [hour, minute, second = 0] = time.split(\":\").map(Number);\n\n if (hour < 0 || hour > 23) {\n throw new Error(`Invalid hour in time \"${time}\". Must be between 0 and 23.`);\n }\n\n if (minute < 0 || minute > 59) {\n throw new Error(`Invalid minute in time \"${time}\". Must be between 0 and 59.`);\n }\n\n if (second < 0 || second > 59) {\n throw new Error(`Invalid second in time \"${time}\". Must be between 0 and 59.`);\n }\n\n return { hour, minute, second };\n}\n\n/**\n * Job class represents a scheduled task with configurable timing and execution options.\n *\n * @example\n * ```typescript\n * const job = new Job(\"cleanup\", async () => {\n * await cleanupOldFiles();\n * })\n * .everyDay()\n * .at(\"03:00\")\n * .inTimezone(\"America/New_York\")\n * .preventOverlap()\n * .retry(3, 1000);\n * ```\n */\nexport class Job {\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Properties\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Interval configuration for scheduling\n */\n private _intervals: JobIntervals = {};\n\n /**\n * Last execution timestamp.\n *\n * Updated after every run attempt — successful or failed — so the next-run\n * calculation always advances even when a job throws. Use the `job:complete`\n * / `job:error` events if you need to distinguish success from failure.\n */\n private _lastRun: Dayjs | null = null;\n\n /**\n * Whether the job is currently executing\n */\n private _isRunning = false;\n\n /**\n * Skip execution if job is already running\n */\n private _skipIfRunning = false;\n\n /**\n * Retry configuration\n */\n private _retryConfig: RetryConfig | null = null;\n\n /**\n * Timezone for scheduling (defaults to UTC)\n */\n private _timezone = \"UTC\";\n\n /**\n * Cron expression parser (mutually exclusive with interval config)\n */\n private _cronParser: CronParser | null = null;\n\n /**\n * All pending `waitForCompletion()` resolvers — drained on every run end.\n */\n private _completionResolvers: (() => void)[] = [];\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Public Properties\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Next scheduled execution time\n */\n public nextRun: Dayjs | null = null;\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Constructor\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Creates a new Job instance\n *\n * @param name - Unique identifier for the job\n * @param callback - Function to execute when the job runs\n */\n public constructor(\n public readonly name: string,\n private readonly _callback: JobCallback,\n ) {}\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Public Getters\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Returns true if the job is currently executing\n */\n public get isRunning(): boolean {\n return this._isRunning;\n }\n\n /**\n * Returns the last execution timestamp (success OR failure).\n */\n public get lastRun(): Dayjs | null {\n return this._lastRun;\n }\n\n /**\n * Returns the current interval configuration (readonly)\n */\n public get intervals(): Readonly<JobIntervals> {\n return this._intervals;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Interval Configuration Methods (Fluent API)\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Set a custom interval for job execution\n *\n * @param value - Number of time units (must be > 0)\n * @param timeType - Type of time unit\n * @returns this for chaining\n * @throws Error if `value` is not a positive finite number\n *\n * @example\n * ```typescript\n * job.every(5, \"minute\"); // Run every 5 minutes\n * job.every(2, \"hour\"); // Run every 2 hours\n * ```\n */\n public every(value: number, timeType: TimeType): this {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(\n `Invalid interval value: ${value}. Must be a positive finite number.`,\n );\n }\n\n this._intervals.every = { type: timeType, value };\n this._determineNextRun();\n\n return this;\n }\n\n /**\n * Run job every second (use with caution - high frequency)\n */\n public everySecond(): this {\n return this.every(1, \"second\");\n }\n\n /**\n * Run job every specified number of seconds\n */\n public everySeconds(seconds: number): this {\n return this.every(seconds, \"second\");\n }\n\n /**\n * Run job every minute\n */\n public everyMinute(): this {\n return this.every(1, \"minute\");\n }\n\n /**\n * Run job every specified number of minutes\n */\n public everyMinutes(minutes: number): this {\n return this.every(minutes, \"minute\");\n }\n\n /**\n * Run job every hour\n */\n public everyHour(): this {\n return this.every(1, \"hour\");\n }\n\n /**\n * Run job every specified number of hours\n */\n public everyHours(hours: number): this {\n return this.every(hours, \"hour\");\n }\n\n /**\n * Run job every day at midnight\n */\n public everyDay(): this {\n return this.every(1, \"day\");\n }\n\n /**\n * Alias for everyDay()\n */\n public daily(): this {\n return this.everyDay();\n }\n\n /**\n * Run job twice a day (every 12 hours)\n */\n public twiceDaily(): this {\n return this.every(12, \"hour\");\n }\n\n /**\n * Run job every week\n */\n public everyWeek(): this {\n return this.every(1, \"week\");\n }\n\n /**\n * Alias for everyWeek()\n */\n public weekly(): this {\n return this.everyWeek();\n }\n\n /**\n * Run job every month\n */\n public everyMonth(): this {\n return this.every(1, \"month\");\n }\n\n /**\n * Alias for everyMonth()\n */\n public monthly(): this {\n return this.everyMonth();\n }\n\n /**\n * Run job every year\n */\n public everyYear(): this {\n return this.every(1, \"year\");\n }\n\n /**\n * Alias for everyYear()\n */\n public yearly(): this {\n return this.everyYear();\n }\n\n /**\n * Alias for everyMinute() - job runs continuously every minute\n */\n public always(): this {\n return this.everyMinute();\n }\n\n /**\n * Schedule job using a cron expression\n *\n * Supports standard 5-field cron syntax:\n * ```\n * ┌───────────── minute (0-59)\n * │ ┌───────────── hour (0-23)\n * │ │ ┌───────────── day of month (1-31)\n * │ │ │ ┌───────────── month (1-12)\n * │ │ │ │ ┌───────────── day of week (0-6, Sunday = 0)\n * │ │ │ │ │\n * * * * * *\n * ```\n *\n * Supports:\n * - '*' - any value\n * - '5' - specific value\n * - '1,3,5' - list of values\n * - '1-5' - range of values\n * - '*/5' - step values (every 5)\n * - '1-10/2' - range with step\n *\n * @param expression - Standard 5-field cron expression\n * @returns this for chaining\n *\n * @example\n * ```typescript\n * job.cron(\"0 9 * * 1-5\"); // 9 AM weekdays\n * job.cron(\"*/5 * * * *\"); // Every 5 minutes\n * job.cron(\"0 0 1 * *\"); // First day of month at midnight\n * job.cron(\"0 */2 * * *\"); // Every 2 hours\n * ```\n */\n public cron(expression: string): this {\n this._cronParser = new CronParser(expression);\n // Clear interval config since cron takes precedence\n this._intervals = {};\n this._determineNextRun();\n return this;\n }\n\n /**\n * Get the cron expression if one is set\n */\n public get cronExpression(): string | null {\n return this._cronParser?.expression ?? null;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Day & Time Configuration Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Schedule job on a specific day\n *\n * @param day - Day of week (string) or day of month (number 1-31)\n * @returns this for chaining\n *\n * @example\n * ```typescript\n * job.on(\"monday\"); // Run on Mondays\n * job.on(15); // Run on the 15th of each month\n * ```\n */\n public on(day: Day | number): this {\n if (typeof day === \"number\" && (day < 1 || day > 31)) {\n throw new Error(\"Invalid day of the month. Must be between 1 and 31.\");\n }\n\n this._intervals.day = day;\n\n if (typeof day === \"number\") {\n this._intervals.dayOfMonthMode = \"specific\";\n }\n\n this._determineNextRun();\n\n return this;\n }\n\n /**\n * Schedule job at a specific time\n *\n * @param time - Time in HH:mm or HH:mm:ss format\n * @returns this for chaining\n *\n * @example\n * ```typescript\n * job.daily().at(\"09:00\"); // Run daily at 9 AM\n * job.weekly().at(\"14:30\"); // Run weekly at 2:30 PM\n * ```\n */\n public at(time: string): this {\n parseTimeString(time);\n this._intervals.time = time;\n this._determineNextRun();\n\n return this;\n }\n\n /**\n * Run task at the beginning of the specified time period.\n *\n * - `\"day\"` → 00:00 every day\n * - `\"month\"` → 1st of every month at 00:00\n * - `\"year\"` → January 1st at 00:00 every year\n *\n * @param type - Time type (day, month, year)\n */\n public beginOf(type: TimeType): this {\n switch (type) {\n case \"day\":\n this._intervals.every = { type: \"day\", value: 1 };\n break;\n\n case \"month\":\n this._intervals.day = 1;\n this._intervals.dayOfMonthMode = \"specific\";\n this._intervals.every = { type: \"month\", value: 1 };\n break;\n\n case \"year\":\n this._intervals.month = 1;\n this._intervals.day = 1;\n this._intervals.dayOfMonthMode = \"specific\";\n this._intervals.every = { type: \"year\", value: 1 };\n break;\n\n default:\n throw new Error(`Unsupported type for beginOf: ${type}`);\n }\n\n return this.at(\"00:00\");\n }\n\n /**\n * Run task at the end of the specified time period.\n *\n * - `\"day\"` → 23:59 every day\n * - `\"month\"` → last day of every month at 23:59 (recomputed each cycle —\n * correct in February vs. March)\n * - `\"year\"` → December 31st at 23:59 every year\n *\n * @param type - Time type (day, month, year)\n */\n public endOf(type: TimeType): this {\n switch (type) {\n case \"day\":\n this._intervals.every = { type: \"day\", value: 1 };\n break;\n\n case \"month\":\n this._intervals.dayOfMonthMode = \"last\";\n this._intervals.every = { type: \"month\", value: 1 };\n break;\n\n case \"year\":\n this._intervals.month = 12;\n this._intervals.day = 31;\n this._intervals.dayOfMonthMode = \"specific\";\n this._intervals.every = { type: \"year\", value: 1 };\n break;\n\n default:\n throw new Error(`Unsupported type for endOf: ${type}`);\n }\n\n return this.at(\"23:59\");\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Timezone Configuration\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Set the timezone for this job's scheduling\n *\n * @param tz - IANA timezone string (e.g., \"America/New_York\", \"Europe/London\")\n * @returns this for chaining\n *\n * @example\n * ```typescript\n * job.daily().at(\"09:00\").inTimezone(\"America/New_York\");\n * ```\n */\n public inTimezone(tz: string): this {\n this._timezone = tz;\n this._determineNextRun();\n return this;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Execution Options\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Prevent overlapping executions of this job.\n *\n * When enabled, if the job is already running when it's scheduled to run again,\n * the new execution will be skipped.\n *\n * @param skip - Whether to skip if already running (default: true)\n * @returns this for chaining\n */\n public preventOverlap(skip = true): this {\n this._skipIfRunning = skip;\n return this;\n }\n\n /**\n * Configure automatic retry on failure\n *\n * @param maxRetries - Maximum number of retry attempts (must be ≥ 0)\n * @param delay - Delay between retries in milliseconds (must be ≥ 0)\n * @param backoffMultiplier - Optional multiplier for exponential backoff (must be > 0)\n * @returns this for chaining\n *\n * @example\n * ```typescript\n * job.retry(3, 1000); // Retry 3 times with 1s delay\n * job.retry(5, 1000, 2); // Exponential backoff: 1s, 2s, 4s, 8s, 16s\n * ```\n */\n public retry(maxRetries: number, delay = 1000, backoffMultiplier?: number): this {\n if (!Number.isFinite(maxRetries) || maxRetries < 0) {\n throw new Error(`Invalid maxRetries: ${maxRetries}. Must be ≥ 0.`);\n }\n\n if (!Number.isFinite(delay) || delay < 0) {\n throw new Error(`Invalid retry delay: ${delay}. Must be ≥ 0.`);\n }\n\n if (\n backoffMultiplier !== undefined &&\n (!Number.isFinite(backoffMultiplier) || backoffMultiplier <= 0)\n ) {\n throw new Error(\n `Invalid backoffMultiplier: ${backoffMultiplier}. Must be > 0.`,\n );\n }\n\n this._retryConfig = {\n maxRetries,\n delay,\n backoffMultiplier,\n };\n\n return this;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Execution Control\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Terminate the job and clear all scheduling data\n */\n public terminate(): this {\n this._intervals = {};\n this._cronParser = null;\n this.nextRun = null;\n this._lastRun = null;\n this._isRunning = false;\n return this;\n }\n\n /**\n * Prepare the job by calculating the next run time\n * Called by the scheduler when starting\n */\n public prepare(): void {\n this._determineNextRun();\n }\n\n /**\n * Returns true if the job's `nextRun` has arrived, regardless of whether\n * it is currently running. Used by the scheduler to decide whether a\n * tick is \"due\" before checking overlap state.\n */\n public isDue(): boolean {\n return this.nextRun !== null && this._now().isSameOrAfter(this.nextRun);\n }\n\n /**\n * Determine if the job should run now.\n *\n * Combines `isDue()` with the overlap-prevention rule: when\n * `preventOverlap()` is on and the job is already running, this returns\n * false even if the next-run time has arrived.\n *\n * @returns true if the job should execute\n */\n public shouldRun(): boolean {\n if (this._skipIfRunning && this._isRunning) {\n return false;\n }\n\n return this.isDue();\n }\n\n /**\n * Execute the job once.\n *\n * Always advances `lastRun` and recalculates `nextRun` (success OR failure)\n * so a permanently failing job does not re-fire on every scheduler tick.\n *\n * @returns Promise resolving to the job result\n */\n public async run(): Promise<JobResult> {\n const startTime = Date.now();\n\n this._isRunning = true;\n\n let result: JobResult;\n let executedRetries = 0;\n\n try {\n const inner = await this._executeWithRetry();\n executedRetries = inner.retries;\n\n result = {\n success: true,\n duration: Date.now() - startTime,\n retries: executedRetries,\n };\n } catch (error) {\n result = {\n success: false,\n duration: Date.now() - startTime,\n error,\n retries: this._retryConfig?.maxRetries ?? 0,\n };\n } finally {\n this._lastRun = this._now();\n this._determineNextRun();\n this._isRunning = false;\n\n // Drain ALL pending waiters (waitForCompletion may be called more than once).\n const resolvers = this._completionResolvers.splice(0);\n\n for (const resolve of resolvers) {\n resolve();\n }\n }\n\n return result;\n }\n\n /**\n * Wait for the currently executing run to complete.\n *\n * Multiple concurrent waiters are all resolved when the run finishes.\n * Useful for graceful shutdown.\n *\n * @returns Promise that resolves when the job completes\n */\n public waitForCompletion(): Promise<void> {\n if (!this._isRunning) {\n return Promise.resolve();\n }\n\n return new Promise(resolve => {\n this._completionResolvers.push(resolve);\n });\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Get current time, respecting the configured timezone.\n */\n private _now(): Dayjs {\n return dayjs().tz(this._timezone);\n }\n\n /**\n * Execute the callback with retry logic\n */\n private async _executeWithRetry(): Promise<{ retries: number }> {\n let lastError: unknown;\n let attempts = 0;\n const maxAttempts = (this._retryConfig?.maxRetries ?? 0) + 1;\n\n while (attempts < maxAttempts) {\n try {\n await this._callback(this);\n return { retries: attempts };\n } catch (error) {\n lastError = error;\n attempts++;\n\n if (attempts < maxAttempts && this._retryConfig) {\n const delay = this._calculateRetryDelay(attempts);\n await this._sleep(delay);\n }\n }\n }\n\n throw lastError;\n }\n\n /**\n * Calculate retry delay with optional exponential backoff\n */\n private _calculateRetryDelay(attempt: number): number {\n if (!this._retryConfig) return 0;\n\n const { delay, backoffMultiplier } = this._retryConfig;\n\n if (backoffMultiplier) {\n return delay * Math.pow(backoffMultiplier, attempt - 1);\n }\n\n return delay;\n }\n\n /**\n * Sleep for specified milliseconds\n */\n private _sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n /**\n * Apply month / day-of-month / day-of-week / time constraints to a Dayjs.\n *\n * Re-applied after every interval advance inside `_determineNextRun` so\n * dynamic constraints (`dayOfMonthMode: \"last\"` recomputed per month, month\n * lock for `beginOf/endOf(\"year\")`) stay correct as the candidate moves\n * forward.\n */\n private _applyConstraints(date: Dayjs): Dayjs {\n let result = date;\n\n if (this._intervals.month !== undefined) {\n result = result.month(this._intervals.month - 1);\n }\n\n if (this._intervals.dayOfMonthMode === \"last\") {\n result = result.date(result.daysInMonth());\n } else if (this._intervals.day !== undefined) {\n if (typeof this._intervals.day === \"number\") {\n result = result.date(this._intervals.day);\n } else {\n const targetDay = DAYS_OF_WEEK.indexOf(this._intervals.day);\n\n if (targetDay !== -1) {\n result = result.day(targetDay);\n }\n }\n }\n\n if (this._intervals.time) {\n const { hour, minute, second } = parseTimeString(this._intervals.time);\n result = result.hour(hour).minute(minute).second(second).millisecond(0);\n }\n\n return result;\n }\n\n /**\n * Calculate the next run time based on interval or cron configuration.\n *\n * Strategy: apply all constraints (month, day, time) ONCE before the\n * advance loop, then advance by `every` until the candidate is in the\n * future. Static constraints (numeric day, fixed month, fixed time)\n * survive `dayjs.add()` automatically. The only dynamic constraint —\n * `dayOfMonthMode: \"last\"` — is re-applied inside the loop so the\n * candidate always lands on the *new* month's last day after each\n * advance.\n *\n * Re-applying time/day inside the loop would deadlock: with\n * `twiceDaily().at(\"06:00\")` we'd advance 06:00 → 18:00 → snap back to\n * 06:00 → 18:00 → ... forever.\n */\n private _determineNextRun(): void {\n if (this._cronParser) {\n const now = this._now();\n this.nextRun = this._cronParser.nextRun(now);\n return;\n }\n\n const intervalValue = this._intervals.every?.value;\n const intervalType = this._intervals.every?.type;\n const hasInterval = !!(intervalValue && intervalType);\n\n // After a previous run, jump ahead by EXACTLY one interval. Previously\n // we used `lastRun + 1s` and relied on the advance loop to catch up,\n // but that loop only triggers when the candidate is in the past — so\n // for fast-completing callbacks the candidate stayed at `lastRun + 1s`,\n // making `everySeconds(2)` fire every second. Honor the interval up\n // front instead.\n let date: Dayjs;\n\n if (this._lastRun && hasInterval) {\n date = this._lastRun.add(intervalValue!, intervalType);\n } else if (this._lastRun) {\n date = this._lastRun.add(1, \"second\");\n } else {\n date = this._now();\n }\n\n date = this._applyConstraints(date);\n\n while (date.isBefore(this._now())) {\n if (hasInterval) {\n date = date.add(intervalValue!, intervalType);\n } else {\n date = date.add(1, \"day\");\n }\n\n if (this._intervals.dayOfMonthMode === \"last\") {\n date = date.date(date.daysInMonth());\n }\n }\n\n this.nextRun = date;\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Factory Function\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Factory function to create a new Job instance\n *\n * @param name - Unique identifier for the job\n * @param callback - Function to execute when the job runs\n * @returns New Job instance\n *\n * @example\n * ```typescript\n * const cleanupJob = job(\"cleanup\", async () => {\n * await db.deleteExpiredTokens();\n * }).daily().at(\"03:00\");\n * ```\n */\nexport function job(name: string, callback: JobCallback): Job {\n return new Job(name, callback);\n}\n"],"mappings":";;;;;;;AAOA,MAAM,OAAO,GAAG;AAChB,MAAM,OAAO,QAAQ;AACrB,MAAM,OAAO,aAAa;;;;AAO1B,MAAM,eAAsB;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAMA,SAAS,gBAAgB,MAIvB;CACA,IAAI,CAAC,2BAA2B,KAAK,IAAI,GACvC,MAAM,IAAI,MAAM,6CAA6C;CAG/D,MAAM,CAAC,MAAM,QAAQ,SAAS,KAAK,KAAK,MAAM,GAAG,EAAE,IAAI,MAAM;CAE7D,IAAI,OAAO,KAAK,OAAO,IACrB,MAAM,IAAI,MAAM,yBAAyB,KAAK,6BAA6B;CAG7E,IAAI,SAAS,KAAK,SAAS,IACzB,MAAM,IAAI,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AAgB,KAAK,WAAW,IAAI;GACrE,SAAS,OAAO,KAAK,IAAI,EAAE,OAAO,MAAM,EAAE,OAAO,MAAM,EAAE,YAAY,CAAC;EACxE;EAEA,OAAO;CACT;;;;;;;;;;;;;;;;CAiBA,AAAQ,oBAA0B;EAChC,IAAI,KAAK,aAAa;GACpB,MAAM,MAAM,KAAK,KAAK;GACtB,KAAK,UAAU,KAAK,YAAY,QAAQ,GAAG;GAC3C;EACF;EAEA,MAAM,gBAAgB,KAAK,WAAW,OAAO;EAC7C,MAAM,eAAe,KAAK,WAAW,OAAO;EAC5C,MAAM,cAAc,CAAC,EAAE,iBAAiB;EAQxC,IAAI;EAEJ,IAAI,KAAK,YAAY,aACnB,OAAO,KAAK,SAAS,IAAI,eAAgB,YAAY;OAChD,IAAI,KAAK,UACd,OAAO,KAAK,SAAS,IAAI,GAAG,QAAQ;OAEpC,OAAO,KAAK,KAAK;EAGnB,OAAO,KAAK,kBAAkB,IAAI;EAElC,OAAO,KAAK,SAAS,KAAK,KAAK,CAAC,GAAG;GACjC,IAAI,aACF,OAAO,KAAK,IAAI,eAAgB,YAAY;QAE5C,OAAO,KAAK,IAAI,GAAG,KAAK;GAG1B,IAAI,KAAK,WAAW,mBAAmB,QACrC,OAAO,KAAK,KAAK,KAAK,YAAY,CAAC;EAEvC;EAEA,KAAK,UAAU;CACjB;AACF;;;;;;;;;;;;;;;AAoBA,SAAgB,IAAI,MAAc,UAA4B;CAC5D,OAAO,IAAI,IAAI,MAAM,QAAQ;AAC/B"}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { SchedulerEvents } from "./types.mjs";
|
|
2
|
+
import { Job, JobCallback } from "./job.mjs";
|
|
3
|
+
|
|
4
|
+
//#region ../../@warlock.js/scheduler/src/scheduler.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Type-safe event emitter interface for Scheduler events
|
|
7
|
+
*/
|
|
8
|
+
interface TypedEventEmitter<TEvents extends Record<string, unknown[]>> {
|
|
9
|
+
on<K extends keyof TEvents>(event: K, listener: (...args: TEvents[K]) => void): this;
|
|
10
|
+
once<K extends keyof TEvents>(event: K, listener: (...args: TEvents[K]) => void): this;
|
|
11
|
+
off<K extends keyof TEvents>(event: K, listener: (...args: TEvents[K]) => void): this;
|
|
12
|
+
emit<K extends keyof TEvents>(event: K, ...args: TEvents[K]): boolean;
|
|
13
|
+
}
|
|
14
|
+
declare const Scheduler_base: new () => TypedEventEmitter<SchedulerEvents>;
|
|
15
|
+
/**
|
|
16
|
+
* Scheduler class manages and executes scheduled jobs.
|
|
17
|
+
*
|
|
18
|
+
* Features:
|
|
19
|
+
* - Event-based observability
|
|
20
|
+
* - Parallel or sequential job execution
|
|
21
|
+
* - Drift compensation for accurate timing
|
|
22
|
+
* - Graceful shutdown with job draining
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```typescript
|
|
26
|
+
* const scheduler = new Scheduler();
|
|
27
|
+
*
|
|
28
|
+
* scheduler.on('job:error', (jobName, error) => {
|
|
29
|
+
* logger.error(`Job ${jobName} failed:`, error);
|
|
30
|
+
* });
|
|
31
|
+
*
|
|
32
|
+
* scheduler
|
|
33
|
+
* .addJob(cleanupJob)
|
|
34
|
+
* .addJob(reportJob)
|
|
35
|
+
* .runInParallel(true)
|
|
36
|
+
* .start();
|
|
37
|
+
*
|
|
38
|
+
* // Graceful shutdown
|
|
39
|
+
* process.on('SIGTERM', () => scheduler.shutdown());
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
declare class Scheduler extends Scheduler_base implements TypedEventEmitter<SchedulerEvents> {
|
|
43
|
+
/**
|
|
44
|
+
* List of registered jobs
|
|
45
|
+
*/
|
|
46
|
+
private _jobs;
|
|
47
|
+
/**
|
|
48
|
+
* Reference to the current timeout for stopping
|
|
49
|
+
*/
|
|
50
|
+
private _timeoutId;
|
|
51
|
+
/**
|
|
52
|
+
* Tick interval in milliseconds (how often to check for due jobs)
|
|
53
|
+
*/
|
|
54
|
+
private _tickInterval;
|
|
55
|
+
/**
|
|
56
|
+
* Whether to run due jobs in parallel
|
|
57
|
+
*/
|
|
58
|
+
private _runInParallel;
|
|
59
|
+
/**
|
|
60
|
+
* Maximum concurrent jobs when running in parallel
|
|
61
|
+
*/
|
|
62
|
+
private _maxConcurrency;
|
|
63
|
+
/**
|
|
64
|
+
* Flag indicating scheduler is shutting down
|
|
65
|
+
*/
|
|
66
|
+
private _isShuttingDown;
|
|
67
|
+
/**
|
|
68
|
+
* Returns true if the scheduler is currently running
|
|
69
|
+
*/
|
|
70
|
+
get isRunning(): boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Returns the number of registered jobs
|
|
73
|
+
*/
|
|
74
|
+
get jobCount(): number;
|
|
75
|
+
/**
|
|
76
|
+
* Add a job to the scheduler
|
|
77
|
+
*
|
|
78
|
+
* @param job - Job instance to schedule
|
|
79
|
+
* @returns this for chaining
|
|
80
|
+
*/
|
|
81
|
+
addJob(job: Job): this;
|
|
82
|
+
/**
|
|
83
|
+
* Alias to create a new job directly and store it
|
|
84
|
+
*/
|
|
85
|
+
newJob(name: string, jobCallback: JobCallback): Job;
|
|
86
|
+
/**
|
|
87
|
+
* Add multiple jobs to the scheduler.
|
|
88
|
+
*
|
|
89
|
+
* If the scheduler is already running, every newly-added job is prepared
|
|
90
|
+
* (its initial `nextRun` is computed) so it begins firing on the next tick.
|
|
91
|
+
*
|
|
92
|
+
* @param jobs - Array of Job instances
|
|
93
|
+
* @returns this for chaining
|
|
94
|
+
*/
|
|
95
|
+
addJobs(jobs: Job[]): this;
|
|
96
|
+
/**
|
|
97
|
+
* Remove a job from the scheduler by name
|
|
98
|
+
*
|
|
99
|
+
* @param jobName - Name of the job to remove
|
|
100
|
+
* @returns true if job was found and removed
|
|
101
|
+
*/
|
|
102
|
+
removeJob(jobName: string): boolean;
|
|
103
|
+
/**
|
|
104
|
+
* Get a job by name
|
|
105
|
+
*
|
|
106
|
+
* @param jobName - Name of the job to find
|
|
107
|
+
* @returns Job instance or undefined
|
|
108
|
+
*/
|
|
109
|
+
getJob(jobName: string): Job | undefined;
|
|
110
|
+
/**
|
|
111
|
+
* Get all registered jobs
|
|
112
|
+
*
|
|
113
|
+
* @returns Array of registered jobs (readonly)
|
|
114
|
+
*/
|
|
115
|
+
list(): readonly Job[];
|
|
116
|
+
/**
|
|
117
|
+
* Set the tick interval (how often to check for due jobs)
|
|
118
|
+
*
|
|
119
|
+
* @param ms - Interval in milliseconds (minimum 100ms)
|
|
120
|
+
* @returns this for chaining
|
|
121
|
+
*/
|
|
122
|
+
runEvery(ms: number): this;
|
|
123
|
+
/**
|
|
124
|
+
* Configure whether jobs should run in parallel
|
|
125
|
+
*
|
|
126
|
+
* @param parallel - Enable parallel execution
|
|
127
|
+
* @param maxConcurrency - Maximum concurrent jobs (default: 10)
|
|
128
|
+
* @returns this for chaining
|
|
129
|
+
*/
|
|
130
|
+
runInParallel(parallel: boolean, maxConcurrency?: number): this;
|
|
131
|
+
/**
|
|
132
|
+
* Start the scheduler
|
|
133
|
+
*
|
|
134
|
+
* @throws Error if scheduler is already running
|
|
135
|
+
*/
|
|
136
|
+
start(): void;
|
|
137
|
+
/**
|
|
138
|
+
* Stop the scheduler immediately.
|
|
139
|
+
*
|
|
140
|
+
* No-op if the scheduler isn't running. Does not wait for in-flight jobs —
|
|
141
|
+
* use `shutdown()` for graceful termination.
|
|
142
|
+
*/
|
|
143
|
+
stop(): void;
|
|
144
|
+
/**
|
|
145
|
+
* Gracefully shutdown the scheduler
|
|
146
|
+
*
|
|
147
|
+
* Stops scheduling new jobs and waits for currently running jobs to complete.
|
|
148
|
+
*
|
|
149
|
+
* @param timeout - Maximum time to wait for jobs (default: 30000ms)
|
|
150
|
+
* @returns Promise that resolves when shutdown is complete
|
|
151
|
+
*/
|
|
152
|
+
shutdown(timeout?: number): Promise<void>;
|
|
153
|
+
/**
|
|
154
|
+
* Schedule the next tick.
|
|
155
|
+
*
|
|
156
|
+
* Drift-compensated: after each tick, the next delay is `tickInterval -
|
|
157
|
+
* elapsed-tick-time` (clamped to 0). A tick that takes 600 ms on a 1 000 ms
|
|
158
|
+
* interval will be followed by a 400 ms delay so the *period* between tick
|
|
159
|
+
* starts averages `tickInterval` instead of `tickInterval + work-time`.
|
|
160
|
+
*/
|
|
161
|
+
private _scheduleTick;
|
|
162
|
+
/**
|
|
163
|
+
* Execute a scheduler tick - check and run due jobs
|
|
164
|
+
*/
|
|
165
|
+
private _tick;
|
|
166
|
+
/**
|
|
167
|
+
* Run jobs sequentially
|
|
168
|
+
*/
|
|
169
|
+
private _runJobsSequentially;
|
|
170
|
+
/**
|
|
171
|
+
* Run jobs in parallel with concurrency limit
|
|
172
|
+
*/
|
|
173
|
+
private _runJobsInParallel;
|
|
174
|
+
/**
|
|
175
|
+
* Run a single job and emit events
|
|
176
|
+
*/
|
|
177
|
+
private _runJob;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Default scheduler instance for simple use cases
|
|
181
|
+
*
|
|
182
|
+
* @example
|
|
183
|
+
* ```typescript
|
|
184
|
+
* import { scheduler, job } from "@warlock.js/scheduler";
|
|
185
|
+
*
|
|
186
|
+
* scheduler.addJob(job("cleanup", cleanupFn).daily());
|
|
187
|
+
* scheduler.start();
|
|
188
|
+
* ```
|
|
189
|
+
*/
|
|
190
|
+
declare const scheduler: Scheduler;
|
|
191
|
+
//#endregion
|
|
192
|
+
export { Scheduler, scheduler };
|
|
193
|
+
//# sourceMappingURL=scheduler.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scheduler.d.mts","names":[],"sources":["../../../../../@warlock.js/scheduler/src/scheduler.ts"],"mappings":";;;;;;AAE0D;UAKhD,iBAAA,iBAAkC,MAAA;EAC1C,EAAA,iBAAmB,OAAA,EAAS,KAAA,EAAO,CAAA,EAAG,QAAA,MAAc,IAAA,EAAM,OAAA,CAAQ,CAAA;EAClE,IAAA,iBAAqB,OAAA,EAAS,KAAA,EAAO,CAAA,EAAG,QAAA,M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A,kBAAA;;;;UAgBA,OAAA;AAAA;;;;;;;;;;;;cA8BH,SAAA,EAAS,SAAkB"}
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { Job } from "./job.mjs";
|
|
2
|
+
import { EventEmitter } from "node:events";
|
|
3
|
+
|
|
4
|
+
//#region ../../@warlock.js/scheduler/src/scheduler.ts
|
|
5
|
+
/**
|
|
6
|
+
* Scheduler class manages and executes scheduled jobs.
|
|
7
|
+
*
|
|
8
|
+
* Features:
|
|
9
|
+
* - Event-based observability
|
|
10
|
+
* - Parallel or sequential job execution
|
|
11
|
+
* - Drift compensation for accurate timing
|
|
12
|
+
* - Graceful shutdown with job draining
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```typescript
|
|
16
|
+
* const scheduler = new Scheduler();
|
|
17
|
+
*
|
|
18
|
+
* scheduler.on('job:error', (jobName, error) => {
|
|
19
|
+
* logger.error(`Job ${jobName} failed:`, error);
|
|
20
|
+
* });
|
|
21
|
+
*
|
|
22
|
+
* scheduler
|
|
23
|
+
* .addJob(cleanupJob)
|
|
24
|
+
* .addJob(reportJob)
|
|
25
|
+
* .runInParallel(true)
|
|
26
|
+
* .start();
|
|
27
|
+
*
|
|
28
|
+
* // Graceful shutdown
|
|
29
|
+
* process.on('SIGTERM', () => scheduler.shutdown());
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
var Scheduler = class extends EventEmitter {
|
|
33
|
+
constructor(..._args) {
|
|
34
|
+
super(..._args);
|
|
35
|
+
this._jobs = [];
|
|
36
|
+
this._timeoutId = null;
|
|
37
|
+
this._tickInterval = 1e3;
|
|
38
|
+
this._runInParallel = false;
|
|
39
|
+
this._maxConcurrency = 10;
|
|
40
|
+
this._isShuttingDown = false;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Returns true if the scheduler is currently running
|
|
44
|
+
*/
|
|
45
|
+
get isRunning() {
|
|
46
|
+
return this._timeoutId !== null;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Returns the number of registered jobs
|
|
50
|
+
*/
|
|
51
|
+
get jobCount() {
|
|
52
|
+
return this._jobs.length;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Add a job to the scheduler
|
|
56
|
+
*
|
|
57
|
+
* @param job - Job instance to schedule
|
|
58
|
+
* @returns this for chaining
|
|
59
|
+
*/
|
|
60
|
+
addJob(job) {
|
|
61
|
+
this._jobs.push(job);
|
|
62
|
+
if (this.isRunning) job.prepare();
|
|
63
|
+
return this;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Alias to create a new job directly and store it
|
|
67
|
+
*/
|
|
68
|
+
newJob(name, jobCallback) {
|
|
69
|
+
const job = new Job(name, jobCallback);
|
|
70
|
+
this.addJob(job);
|
|
71
|
+
return job;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Add multiple jobs to the scheduler.
|
|
75
|
+
*
|
|
76
|
+
* If the scheduler is already running, every newly-added job is prepared
|
|
77
|
+
* (its initial `nextRun` is computed) so it begins firing on the next tick.
|
|
78
|
+
*
|
|
79
|
+
* @param jobs - Array of Job instances
|
|
80
|
+
* @returns this for chaining
|
|
81
|
+
*/
|
|
82
|
+
addJobs(jobs) {
|
|
83
|
+
this._jobs.push(...jobs);
|
|
84
|
+
if (this.isRunning) for (const job of jobs) job.prepare();
|
|
85
|
+
return this;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Remove a job from the scheduler by name
|
|
89
|
+
*
|
|
90
|
+
* @param jobName - Name of the job to remove
|
|
91
|
+
* @returns true if job was found and removed
|
|
92
|
+
*/
|
|
93
|
+
removeJob(jobName) {
|
|
94
|
+
const index = this._jobs.findIndex((j) => j.name === jobName);
|
|
95
|
+
if (index !== -1) {
|
|
96
|
+
this._jobs.splice(index, 1);
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Get a job by name
|
|
103
|
+
*
|
|
104
|
+
* @param jobName - Name of the job to find
|
|
105
|
+
* @returns Job instance or undefined
|
|
106
|
+
*/
|
|
107
|
+
getJob(jobName) {
|
|
108
|
+
return this._jobs.find((j) => j.name === jobName);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Get all registered jobs
|
|
112
|
+
*
|
|
113
|
+
* @returns Array of registered jobs (readonly)
|
|
114
|
+
*/
|
|
115
|
+
list() {
|
|
116
|
+
return this._jobs;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Set the tick interval (how often to check for due jobs)
|
|
120
|
+
*
|
|
121
|
+
* @param ms - Interval in milliseconds (minimum 100ms)
|
|
122
|
+
* @returns this for chaining
|
|
123
|
+
*/
|
|
124
|
+
runEvery(ms) {
|
|
125
|
+
if (ms < 100) throw new Error("Tick interval must be at least 100ms");
|
|
126
|
+
this._tickInterval = ms;
|
|
127
|
+
return this;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Configure whether jobs should run in parallel
|
|
131
|
+
*
|
|
132
|
+
* @param parallel - Enable parallel execution
|
|
133
|
+
* @param maxConcurrency - Maximum concurrent jobs (default: 10)
|
|
134
|
+
* @returns this for chaining
|
|
135
|
+
*/
|
|
136
|
+
runInParallel(parallel, maxConcurrency = 10) {
|
|
137
|
+
this._runInParallel = parallel;
|
|
138
|
+
this._maxConcurrency = maxConcurrency;
|
|
139
|
+
return this;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Start the scheduler
|
|
143
|
+
*
|
|
144
|
+
* @throws Error if scheduler is already running
|
|
145
|
+
*/
|
|
146
|
+
start() {
|
|
147
|
+
if (this.isRunning) throw new Error("Scheduler is already running.");
|
|
148
|
+
if (this._jobs.length === 0) throw new Error("Cannot start scheduler with no jobs.");
|
|
149
|
+
for (const job of this._jobs) job.prepare();
|
|
150
|
+
this._isShuttingDown = false;
|
|
151
|
+
this._scheduleTick(this._tickInterval);
|
|
152
|
+
this.emit("scheduler:started");
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Stop the scheduler immediately.
|
|
156
|
+
*
|
|
157
|
+
* No-op if the scheduler isn't running. Does not wait for in-flight jobs —
|
|
158
|
+
* use `shutdown()` for graceful termination.
|
|
159
|
+
*/
|
|
160
|
+
stop() {
|
|
161
|
+
if (!this._timeoutId) return;
|
|
162
|
+
clearTimeout(this._timeoutId);
|
|
163
|
+
this._timeoutId = null;
|
|
164
|
+
this.emit("scheduler:stopped");
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Gracefully shutdown the scheduler
|
|
168
|
+
*
|
|
169
|
+
* Stops scheduling new jobs and waits for currently running jobs to complete.
|
|
170
|
+
*
|
|
171
|
+
* @param timeout - Maximum time to wait for jobs (default: 30000ms)
|
|
172
|
+
* @returns Promise that resolves when shutdown is complete
|
|
173
|
+
*/
|
|
174
|
+
async shutdown(timeout = 3e4) {
|
|
175
|
+
this._isShuttingDown = true;
|
|
176
|
+
this.stop();
|
|
177
|
+
const runningJobs = this._jobs.filter((j) => j.isRunning);
|
|
178
|
+
if (runningJobs.length > 0) await Promise.race([Promise.all(runningJobs.map((j) => j.waitForCompletion())), new Promise((resolve) => setTimeout(resolve, timeout))]);
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Schedule the next tick.
|
|
182
|
+
*
|
|
183
|
+
* Drift-compensated: after each tick, the next delay is `tickInterval -
|
|
184
|
+
* elapsed-tick-time` (clamped to 0). A tick that takes 600 ms on a 1 000 ms
|
|
185
|
+
* interval will be followed by a 400 ms delay so the *period* between tick
|
|
186
|
+
* starts averages `tickInterval` instead of `tickInterval + work-time`.
|
|
187
|
+
*/
|
|
188
|
+
_scheduleTick(delay) {
|
|
189
|
+
if (this._isShuttingDown) return;
|
|
190
|
+
this._timeoutId = setTimeout(async () => {
|
|
191
|
+
const tickStart = Date.now();
|
|
192
|
+
await this._tick();
|
|
193
|
+
const elapsed = Date.now() - tickStart;
|
|
194
|
+
const nextDelay = Math.max(this._tickInterval - elapsed, 0);
|
|
195
|
+
this._scheduleTick(nextDelay);
|
|
196
|
+
}, delay);
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Execute a scheduler tick - check and run due jobs
|
|
200
|
+
*/
|
|
201
|
+
async _tick() {
|
|
202
|
+
this.emit("scheduler:tick", /* @__PURE__ */ new Date());
|
|
203
|
+
const dueJobs = this._jobs.filter((job) => {
|
|
204
|
+
if (!job.isDue()) return false;
|
|
205
|
+
if (job.isRunning) {
|
|
206
|
+
this.emit("job:skip", job.name, "Job is already running");
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
return true;
|
|
210
|
+
});
|
|
211
|
+
if (dueJobs.length === 0) return;
|
|
212
|
+
if (this._runInParallel) await this._runJobsInParallel(dueJobs);
|
|
213
|
+
else await this._runJobsSequentially(dueJobs);
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Run jobs sequentially
|
|
217
|
+
*/
|
|
218
|
+
async _runJobsSequentially(jobs) {
|
|
219
|
+
for (const job of jobs) {
|
|
220
|
+
if (this._isShuttingDown) break;
|
|
221
|
+
await this._runJob(job);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Run jobs in parallel with concurrency limit
|
|
226
|
+
*/
|
|
227
|
+
async _runJobsInParallel(jobs) {
|
|
228
|
+
const batches = [];
|
|
229
|
+
for (let i = 0; i < jobs.length; i += this._maxConcurrency) batches.push(jobs.slice(i, i + this._maxConcurrency));
|
|
230
|
+
for (const batch of batches) {
|
|
231
|
+
if (this._isShuttingDown) break;
|
|
232
|
+
await Promise.allSettled(batch.map((job) => this._runJob(job)));
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Run a single job and emit events
|
|
237
|
+
*/
|
|
238
|
+
async _runJob(job) {
|
|
239
|
+
this.emit("job:start", job.name);
|
|
240
|
+
const result = await job.run();
|
|
241
|
+
if (result.success) this.emit("job:complete", job.name, result);
|
|
242
|
+
else this.emit("job:error", job.name, result.error);
|
|
243
|
+
return result;
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
/**
|
|
247
|
+
* Default scheduler instance for simple use cases
|
|
248
|
+
*
|
|
249
|
+
* @example
|
|
250
|
+
* ```typescript
|
|
251
|
+
* import { scheduler, job } from "@warlock.js/scheduler";
|
|
252
|
+
*
|
|
253
|
+
* scheduler.addJob(job("cleanup", cleanupFn).daily());
|
|
254
|
+
* scheduler.start();
|
|
255
|
+
* ```
|
|
256
|
+
*/
|
|
257
|
+
const scheduler = new Scheduler();
|
|
258
|
+
|
|
259
|
+
//#endregion
|
|
260
|
+
export { Scheduler, scheduler };
|
|
261
|
+
//# sourceMappingURL=scheduler.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scheduler.mjs","names":[],"sources":["../../../../../@warlock.js/scheduler/src/scheduler.ts"],"sourcesContent":["import { EventEmitter } from \"node:events\";\nimport { Job, JobCallback } from \"./job\";\nimport type { JobResult, SchedulerEvents } from \"./types\";\n\n/**\n * Type-safe event emitter interface for Scheduler events\n */\ninterface TypedEventEmitter<TEvents extends Record<string, unknown[]>> {\n on<K extends keyof TEvents>(event: K, listener: (...args: TEvents[K]) => void): this;\n once<K extends keyof TEvents>(event: K, listener: (...args: TEvents[K]) => void): this;\n off<K extends keyof TEvents>(event: K, listener: (...args: TEvents[K]) => void): this;\n emit<K extends keyof TEvents>(event: K, ...args: TEvents[K]): boolean;\n}\n\n/**\n * Scheduler class manages and executes scheduled jobs.\n *\n * Features:\n * - Event-based observability\n * - Parallel or sequential job execution\n * - Drift compensation for accurate timing\n * - Graceful shutdown with job draining\n *\n * @example\n * ```typescript\n * const scheduler = new Scheduler();\n *\n * scheduler.on('job:error', (jobName, error) => {\n * logger.error(`Job ${jobName} failed:`, error);\n * });\n *\n * scheduler\n * .addJob(cleanupJob)\n * .addJob(reportJob)\n * .runInParallel(true)\n * .start();\n *\n * // Graceful shutdown\n * process.on('SIGTERM', () => scheduler.shutdown());\n * ```\n */\nexport class Scheduler\n extends (EventEmitter as new () => TypedEventEmitter<SchedulerEvents>)\n implements TypedEventEmitter<SchedulerEvents>\n{\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Properties\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * List of registered jobs\n */\n private _jobs: Job[] = [];\n\n /**\n * Reference to the current timeout for stopping\n */\n private _timeoutId: NodeJS.Timeout | null = null;\n\n /**\n * Tick interval in milliseconds (how often to check for due jobs)\n */\n private _tickInterval = 1000;\n\n /**\n * Whether to run due jobs in parallel\n */\n private _runInParallel = false;\n\n /**\n * Maximum concurrent jobs when running in parallel\n */\n private _maxConcurrency = 10;\n\n /**\n * Flag indicating scheduler is shutting down\n */\n private _isShuttingDown = false;\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Public Getters\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Returns true if the scheduler is currently running\n */\n public get isRunning(): boolean {\n return this._timeoutId !== null;\n }\n\n /**\n * Returns the number of registered jobs\n */\n public get jobCount(): number {\n return this._jobs.length;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Configuration Methods (Fluent API)\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Add a job to the scheduler\n *\n * @param job - Job instance to schedule\n * @returns this for chaining\n */\n public addJob(job: Job): this {\n this._jobs.push(job);\n\n if (this.isRunning) {\n job.prepare();\n }\n\n return this;\n }\n\n /**\n * Alias to create a new job directly and store it\n */\n public newJob(name: string, jobCallback: JobCallback) {\n const job = new Job(name, jobCallback);\n this.addJob(job);\n return job;\n }\n\n /**\n * Add multiple jobs to the scheduler.\n *\n * If the scheduler is already running, every newly-added job is prepared\n * (its initial `nextRun` is computed) so it begins firing on the next tick.\n *\n * @param jobs - Array of Job instances\n * @returns this for chaining\n */\n public addJobs(jobs: Job[]): this {\n this._jobs.push(...jobs);\n\n if (this.isRunning) {\n for (const job of jobs) {\n job.prepare();\n }\n }\n\n return this;\n }\n\n /**\n * Remove a job from the scheduler by name\n *\n * @param jobName - Name of the job to remove\n * @returns true if job was found and removed\n */\n public removeJob(jobName: string): boolean {\n const index = this._jobs.findIndex(j => j.name === jobName);\n\n if (index !== -1) {\n this._jobs.splice(index, 1);\n return true;\n }\n\n return false;\n }\n\n /**\n * Get a job by name\n *\n * @param jobName - Name of the job to find\n * @returns Job instance or undefined\n */\n public getJob(jobName: string): Job | undefined {\n return this._jobs.find(j => j.name === jobName);\n }\n\n /**\n * Get all registered jobs\n *\n * @returns Array of registered jobs (readonly)\n */\n public list(): readonly Job[] {\n return this._jobs;\n }\n\n /**\n * Set the tick interval (how often to check for due jobs)\n *\n * @param ms - Interval in milliseconds (minimum 100ms)\n * @returns this for chaining\n */\n public runEvery(ms: number): this {\n if (ms < 100) {\n throw new Error(\"Tick interval must be at least 100ms\");\n }\n\n this._tickInterval = ms;\n return this;\n }\n\n /**\n * Configure whether jobs should run in parallel\n *\n * @param parallel - Enable parallel execution\n * @param maxConcurrency - Maximum concurrent jobs (default: 10)\n * @returns this for chaining\n */\n public runInParallel(parallel: boolean, maxConcurrency = 10): this {\n this._runInParallel = parallel;\n this._maxConcurrency = maxConcurrency;\n return this;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Lifecycle Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Start the scheduler\n *\n * @throws Error if scheduler is already running\n */\n public start(): void {\n if (this.isRunning) {\n throw new Error(\"Scheduler is already running.\");\n }\n\n if (this._jobs.length === 0) {\n throw new Error(\"Cannot start scheduler with no jobs.\");\n }\n\n for (const job of this._jobs) {\n job.prepare();\n }\n\n this._isShuttingDown = false;\n this._scheduleTick(this._tickInterval);\n\n this.emit(\"scheduler:started\");\n }\n\n /**\n * Stop the scheduler immediately.\n *\n * No-op if the scheduler isn't running. Does not wait for in-flight jobs —\n * use `shutdown()` for graceful termination.\n */\n public stop(): void {\n if (!this._timeoutId) return;\n\n clearTimeout(this._timeoutId);\n this._timeoutId = null;\n\n this.emit(\"scheduler:stopped\");\n }\n\n /**\n * Gracefully shutdown the scheduler\n *\n * Stops scheduling new jobs and waits for currently running jobs to complete.\n *\n * @param timeout - Maximum time to wait for jobs (default: 30000ms)\n * @returns Promise that resolves when shutdown is complete\n */\n public async shutdown(timeout = 30000): Promise<void> {\n this._isShuttingDown = true;\n this.stop();\n\n const runningJobs = this._jobs.filter(j => j.isRunning);\n\n if (runningJobs.length > 0) {\n await Promise.race([\n Promise.all(runningJobs.map(j => j.waitForCompletion())),\n new Promise<void>(resolve => setTimeout(resolve, timeout)),\n ]);\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Private Methods\n // ─────────────────────────────────────────────────────────────────────────────\n\n /**\n * Schedule the next tick.\n *\n * Drift-compensated: after each tick, the next delay is `tickInterval -\n * elapsed-tick-time` (clamped to 0). A tick that takes 600 ms on a 1 000 ms\n * interval will be followed by a 400 ms delay so the *period* between tick\n * starts averages `tickInterval` instead of `tickInterval + work-time`.\n */\n private _scheduleTick(delay: number): void {\n if (this._isShuttingDown) return;\n\n this._timeoutId = setTimeout(async () => {\n const tickStart = Date.now();\n\n await this._tick();\n\n const elapsed = Date.now() - tickStart;\n const nextDelay = Math.max(this._tickInterval - elapsed, 0);\n\n this._scheduleTick(nextDelay);\n }, delay);\n }\n\n /**\n * Execute a scheduler tick - check and run due jobs\n */\n private async _tick(): Promise<void> {\n this.emit(\"scheduler:tick\", new Date());\n\n const dueJobs = this._jobs.filter(job => {\n // Time-based readiness only; running state is checked below so a\n // `job:skip` event fires whenever overlap blocks a due run.\n if (!job.isDue()) return false;\n\n if (job.isRunning) {\n this.emit(\"job:skip\", job.name, \"Job is already running\");\n return false;\n }\n\n return true;\n });\n\n if (dueJobs.length === 0) return;\n\n if (this._runInParallel) {\n await this._runJobsInParallel(dueJobs);\n } else {\n await this._runJobsSequentially(dueJobs);\n }\n }\n\n /**\n * Run jobs sequentially\n */\n private async _runJobsSequentially(jobs: Job[]): Promise<void> {\n for (const job of jobs) {\n if (this._isShuttingDown) break;\n await this._runJob(job);\n }\n }\n\n /**\n * Run jobs in parallel with concurrency limit\n */\n private async _runJobsInParallel(jobs: Job[]): Promise<void> {\n const batches: Job[][] = [];\n\n for (let i = 0; i < jobs.length; i += this._maxConcurrency) {\n batches.push(jobs.slice(i, i + this._maxConcurrency));\n }\n\n for (const batch of batches) {\n if (this._isShuttingDown) break;\n await Promise.allSettled(batch.map(job => this._runJob(job)));\n }\n }\n\n /**\n * Run a single job and emit events\n */\n private async _runJob(job: Job): Promise<JobResult> {\n this.emit(\"job:start\", job.name);\n\n const result = await job.run();\n\n if (result.success) {\n this.emit(\"job:complete\", job.name, result);\n } else {\n this.emit(\"job:error\", job.name, result.error);\n }\n\n return result;\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Default Export\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Default scheduler instance for simple use cases\n *\n * @example\n * ```typescript\n * import { scheduler, job } from \"@warlock.js/scheduler\";\n *\n * scheduler.addJob(job(\"cleanup\", cleanupFn).daily());\n * scheduler.start();\n * ```\n */\nexport const scheduler = new Scheduler();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAa,YAAb,cACW,aAEX;;;eAQyB,CAAC;oBAKoB;uBAKpB;wBAKC;yBAKC;yBAKA;;;;;CAS1B,IAAW,YAAqB;EAC9B,OAAO,KAAK,eAAe;CAC7B;;;;CAKA,IAAW,WAAmB;EAC5B,OAAO,KAAK,MAAM;CACpB;;;;;;;CAYA,AAAO,OAAO,KAAgB;EAC5B,KAAK,MAAM,KAAK,GAAG;EAEnB,IAAI,KAAK,WACP,IAAI,QAAQ;EAGd,OAAO;CACT;;;;CAKA,AAAO,OAAO,MAAc,aAA0B;EACpD,MAAM,MAAM,IAAI,IAAI,MAAM,WAAW;EACrC,KAAK,OAAO,GAAG;EACf,OAAO;C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3B,IAAI,KAAK,iBAAiB;GAC1B,MAAM,QAAQ,WAAW,MAAM,KAAI,QAAO,KAAK,QAAQ,GAAG,CAAC,CAAC;EAC9D;CACF;;;;CAKA,MAAc,QAAQ,KAA8B;EAClD,KAAK,KAAK,aAAa,IAAI,IAAI;EAE/B,MAAM,SAAS,MAAM,IAAI,IAAI;EAE7B,IAAI,OAAO,SACT,KAAK,KAAK,gBAAgB,IAAI,MAAM,MAAM;OAE1C,KAAK,KAAK,aAAa,IAAI,MAAM,OAAO,KAAK;EAG/C,OAAO;CACT;AACF;;;;;;;;;;;;AAiBA,MAAa,YAAY,IAAI,UAAU"}
|
package/esm/types.d.mts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
//#region ../../@warlock.js/scheduler/src/types.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Time unit types for scheduling intervals
|
|
4
|
+
*/
|
|
5
|
+
type TimeType = "second" | "minute" | "hour" | "day" | "week" | "month" | "year";
|
|
6
|
+
/**
|
|
7
|
+
* Days of the week (lowercase for consistency)
|
|
8
|
+
*/
|
|
9
|
+
type Day = "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday";
|
|
10
|
+
/**
|
|
11
|
+
* How the day-of-month constraint is interpreted.
|
|
12
|
+
*
|
|
13
|
+
* - `"specific"` — `day` is a fixed day number (1–31).
|
|
14
|
+
* - `"last"` — recompute each cycle as the last day of the current month
|
|
15
|
+
* (so `endOf("month")` is correct in February vs. March).
|
|
16
|
+
*/
|
|
17
|
+
type DayOfMonthMode = "specific" | "last";
|
|
18
|
+
/**
|
|
19
|
+
* Job interval configuration
|
|
20
|
+
*/
|
|
21
|
+
type JobIntervals = {
|
|
22
|
+
/** Day of week (string) or day of month (1–31) */day?: Day | number;
|
|
23
|
+
/**
|
|
24
|
+
* Day-of-month interpretation. Defaults to `"specific"` when `day` is a
|
|
25
|
+
* number. `"last"` overrides `day` and resolves to `daysInMonth()` per cycle.
|
|
26
|
+
*/
|
|
27
|
+
dayOfMonthMode?: DayOfMonthMode; /** Month constraint (1–12). Used by `beginOf`/`endOf` of `"year"`. */
|
|
28
|
+
month?: number; /** Time of day in HH:mm or HH:mm:ss format */
|
|
29
|
+
time?: string; /** Recurring interval configuration */
|
|
30
|
+
every?: {
|
|
31
|
+
type?: TimeType;
|
|
32
|
+
value?: number;
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Result of a job execution
|
|
37
|
+
*/
|
|
38
|
+
type JobResult = {
|
|
39
|
+
/** Whether the job completed successfully */success: boolean; /** Execution duration in milliseconds */
|
|
40
|
+
duration: number; /** Error if the job failed */
|
|
41
|
+
error?: unknown; /** Number of retry attempts made */
|
|
42
|
+
retries?: number;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Job execution status
|
|
46
|
+
*/
|
|
47
|
+
type JobStatus = "idle" | "running" | "completed" | "failed";
|
|
48
|
+
/**
|
|
49
|
+
* Retry configuration for jobs
|
|
50
|
+
*/
|
|
51
|
+
type RetryConfig = {
|
|
52
|
+
/** Maximum number of retry attempts */maxRetries: number; /** Delay between retries in milliseconds */
|
|
53
|
+
delay: number; /** Backoff multiplier for exponential backoff */
|
|
54
|
+
backoffMultiplier?: number;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Scheduler event types for observability
|
|
58
|
+
*/
|
|
59
|
+
type SchedulerEvents = {
|
|
60
|
+
"job:start": [jobName: string];
|
|
61
|
+
"job:complete": [jobName: string, result: JobResult];
|
|
62
|
+
"job:error": [jobName: string, error: unknown];
|
|
63
|
+
"job:skip": [jobName: string, reason: string];
|
|
64
|
+
"scheduler:started": [];
|
|
65
|
+
"scheduler:stopped": [];
|
|
66
|
+
"scheduler:tick": [timestamp: Date];
|
|
67
|
+
};
|
|
68
|
+
//#endregion
|
|
69
|
+
export { Day, JobIntervals, JobResult, JobStatus, RetryConfig, SchedulerEvents, TimeType };
|
|
70
|
+
//# sourceMappingURL=types.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../@warlock.js/scheduler/src/types.ts"],"mappings":";;AAGA;;KAAY,QAAA;;AAAQ;AAKpB;KAAY,GAAA;;;AAAG;AAgBf;;;;KAAY,cAAA;AAKZ;;;AAAA,KAAY,YAAA;EAOO,kDALjB,GAAA,GAAM,GAAA;EAYW;;;;EAPjB,cAAA,GAAiB,cAAA,EAAA;EAEjB,KAAA,WAEA;EAAA,IAAA,WAGE;EADF,KAAA;IACE,IAAA,GAAO,QAAA;IACP,KAAA;EAAA;AAAA;;;;KAOQ,SAAA;EAIV,6CAFA,OAAA,WAMA;EAJA,QAAA,UAIO;EAFP,KAAA,YAQmB;EANnB,OAAA;AAAA;AAMmB;AAKrB;;AALqB,KAAT,SAAA;;;;KAKA,WAAA;EAMO,uCAJjB,UAAA,UAUU;EARV,KAAA;EAEA,iBAAA;AAAA;;;;KAMU,eAAA;EACV,WAAA,GAAc,OAAA;EACd,cAAA,GAAiB,OAAA,UAAiB,MAAA,EAAQ,SAAA;EAC1C,WAAA,GAAc,OAAA,UAAiB,KAAA;EAC/B,UAAA,GAAa,OAAA,UAAiB,MAAA;EAC9B,mBAAA;EACA,mBAAA;EACA,gBAAA,GAAmB,SAAA,EAAW,IAAI;AAAA"}
|