@warlock.js/scheduler 4.0.39 → 4.0.41
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/cjs/index.js +976 -1
- package/cjs/index.js.map +1 -1
- package/esm/index.js +963 -1
- package/esm/index.js.map +1 -1
- package/package.json +1 -1
package/esm/index.js
CHANGED
|
@@ -1,2 +1,964 @@
|
|
|
1
|
-
import
|
|
1
|
+
import dayjs2 from 'dayjs';
|
|
2
|
+
import timezone from 'dayjs/plugin/timezone.js';
|
|
3
|
+
import utc from 'dayjs/plugin/utc.js';
|
|
4
|
+
import { EventEmitter } from 'events';
|
|
5
|
+
|
|
6
|
+
// ../../warlock.js/scheduler/src/cron-parser.ts
|
|
7
|
+
var CronParser = class {
|
|
8
|
+
/**
|
|
9
|
+
* Creates a new CronParser instance
|
|
10
|
+
*
|
|
11
|
+
* @param expression - Standard 5-field cron expression
|
|
12
|
+
* @throws Error if expression is invalid
|
|
13
|
+
*/
|
|
14
|
+
constructor(_expression) {
|
|
15
|
+
this._expression = _expression;
|
|
16
|
+
this._fields = this._parse(_expression);
|
|
17
|
+
}
|
|
18
|
+
_fields;
|
|
19
|
+
/**
|
|
20
|
+
* Get the parsed cron fields
|
|
21
|
+
*/
|
|
22
|
+
get fields() {
|
|
23
|
+
return this._fields;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Get the original expression
|
|
27
|
+
*/
|
|
28
|
+
get expression() {
|
|
29
|
+
return this._expression;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Calculate the next run time from a given date
|
|
33
|
+
*
|
|
34
|
+
* @param from - Starting date (defaults to now)
|
|
35
|
+
* @returns Next run time as Dayjs
|
|
36
|
+
*/
|
|
37
|
+
nextRun(from = dayjs2()) {
|
|
38
|
+
let date = from.add(1, "minute").second(0).millisecond(0);
|
|
39
|
+
const maxIterations = 366 * 24 * 60;
|
|
40
|
+
let iterations = 0;
|
|
41
|
+
while (iterations < maxIterations) {
|
|
42
|
+
iterations++;
|
|
43
|
+
if (!this._fields.months.includes(date.month() + 1)) {
|
|
44
|
+
date = date.add(1, "month").date(1).hour(0).minute(0);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (!this._fields.daysOfMonth.includes(date.date())) {
|
|
48
|
+
date = date.add(1, "day").hour(0).minute(0);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (!this._fields.daysOfWeek.includes(date.day())) {
|
|
52
|
+
date = date.add(1, "day").hour(0).minute(0);
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (!this._fields.hours.includes(date.hour())) {
|
|
56
|
+
date = date.add(1, "hour").minute(0);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (!this._fields.minutes.includes(date.minute())) {
|
|
60
|
+
date = date.add(1, "minute");
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
return date;
|
|
64
|
+
}
|
|
65
|
+
throw new Error(`Could not find next run time for cron expression: ${this._expression}`);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Check if a given date matches the cron expression
|
|
69
|
+
*
|
|
70
|
+
* @param date - Date to check
|
|
71
|
+
* @returns true if the date matches
|
|
72
|
+
*/
|
|
73
|
+
matches(date) {
|
|
74
|
+
return this._fields.minutes.includes(date.minute()) && this._fields.hours.includes(date.hour()) && this._fields.daysOfMonth.includes(date.date()) && this._fields.months.includes(date.month() + 1) && this._fields.daysOfWeek.includes(date.day());
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Parse a cron expression into fields
|
|
78
|
+
*/
|
|
79
|
+
_parse(expression) {
|
|
80
|
+
const parts = expression.trim().split(/\s+/);
|
|
81
|
+
if (parts.length !== 5) {
|
|
82
|
+
throw new Error(
|
|
83
|
+
`Invalid cron expression: "${expression}". Expected 5 fields (minute hour day month weekday).`
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
const [minute, hour, dayOfMonth, month, dayOfWeek] = parts;
|
|
87
|
+
return {
|
|
88
|
+
minutes: this._parseField(minute, 0, 59),
|
|
89
|
+
hours: this._parseField(hour, 0, 23),
|
|
90
|
+
daysOfMonth: this._parseField(dayOfMonth, 1, 31),
|
|
91
|
+
months: this._parseField(month, 1, 12),
|
|
92
|
+
daysOfWeek: this._parseField(dayOfWeek, 0, 6)
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Parse a single cron field
|
|
97
|
+
*
|
|
98
|
+
* @param field - Field value (e.g., "*", "5", "1-5", "* /2", "1,3,5")
|
|
99
|
+
* @param min - Minimum allowed value
|
|
100
|
+
* @param max - Maximum allowed value
|
|
101
|
+
* @returns Array of matching values
|
|
102
|
+
*/
|
|
103
|
+
_parseField(field, min, max) {
|
|
104
|
+
const values = /* @__PURE__ */ new Set();
|
|
105
|
+
const parts = field.split(",");
|
|
106
|
+
for (const part of parts) {
|
|
107
|
+
const [range, stepStr] = part.split("/");
|
|
108
|
+
const step = stepStr ? parseInt(stepStr, 10) : 1;
|
|
109
|
+
if (isNaN(step) || step < 1) {
|
|
110
|
+
throw new Error(`Invalid step value in cron field: "${field}"`);
|
|
111
|
+
}
|
|
112
|
+
let rangeStart;
|
|
113
|
+
let rangeEnd;
|
|
114
|
+
if (range === "*") {
|
|
115
|
+
rangeStart = min;
|
|
116
|
+
rangeEnd = max;
|
|
117
|
+
} else if (range.includes("-")) {
|
|
118
|
+
const [startStr, endStr] = range.split("-");
|
|
119
|
+
rangeStart = parseInt(startStr, 10);
|
|
120
|
+
rangeEnd = parseInt(endStr, 10);
|
|
121
|
+
if (isNaN(rangeStart) || isNaN(rangeEnd)) {
|
|
122
|
+
throw new Error(`Invalid range in cron field: "${field}"`);
|
|
123
|
+
}
|
|
124
|
+
if (rangeStart < min || rangeEnd > max || rangeStart > rangeEnd) {
|
|
125
|
+
throw new Error(`Range out of bounds in cron field: "${field}" (valid: ${min}-${max})`);
|
|
126
|
+
}
|
|
127
|
+
} else {
|
|
128
|
+
const value = parseInt(range, 10);
|
|
129
|
+
if (isNaN(value)) {
|
|
130
|
+
throw new Error(`Invalid value in cron field: "${field}"`);
|
|
131
|
+
}
|
|
132
|
+
if (value < min || value > max) {
|
|
133
|
+
throw new Error(`Value out of bounds in cron field: "${field}" (valid: ${min}-${max})`);
|
|
134
|
+
}
|
|
135
|
+
rangeStart = value;
|
|
136
|
+
rangeEnd = value;
|
|
137
|
+
}
|
|
138
|
+
for (let i = rangeStart; i <= rangeEnd; i += step) {
|
|
139
|
+
values.add(i);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return Array.from(values).sort((a, b) => a - b);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
function parseCron(expression) {
|
|
146
|
+
return new CronParser(expression);
|
|
147
|
+
}
|
|
148
|
+
dayjs2.extend(utc);
|
|
149
|
+
dayjs2.extend(timezone);
|
|
150
|
+
var DAYS_OF_WEEK = [
|
|
151
|
+
"sunday",
|
|
152
|
+
"monday",
|
|
153
|
+
"tuesday",
|
|
154
|
+
"wednesday",
|
|
155
|
+
"thursday",
|
|
156
|
+
"friday",
|
|
157
|
+
"saturday"
|
|
158
|
+
];
|
|
159
|
+
var Job = class {
|
|
160
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
161
|
+
// Constructor
|
|
162
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
163
|
+
/**
|
|
164
|
+
* Creates a new Job instance
|
|
165
|
+
*
|
|
166
|
+
* @param name - Unique identifier for the job
|
|
167
|
+
* @param callback - Function to execute when the job runs
|
|
168
|
+
*/
|
|
169
|
+
constructor(name, _callback) {
|
|
170
|
+
this.name = name;
|
|
171
|
+
this._callback = _callback;
|
|
172
|
+
}
|
|
173
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
174
|
+
// Private Properties
|
|
175
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
176
|
+
/**
|
|
177
|
+
* Interval configuration for scheduling
|
|
178
|
+
*/
|
|
179
|
+
_intervals = {};
|
|
180
|
+
/**
|
|
181
|
+
* Last execution timestamp
|
|
182
|
+
*/
|
|
183
|
+
_lastRun = null;
|
|
184
|
+
/**
|
|
185
|
+
* Whether the job is currently executing
|
|
186
|
+
*/
|
|
187
|
+
_isRunning = false;
|
|
188
|
+
/**
|
|
189
|
+
* Skip execution if job is already running
|
|
190
|
+
*/
|
|
191
|
+
_skipIfRunning = false;
|
|
192
|
+
/**
|
|
193
|
+
* Retry configuration
|
|
194
|
+
*/
|
|
195
|
+
_retryConfig = null;
|
|
196
|
+
/**
|
|
197
|
+
* Timezone for scheduling (defaults to system timezone)
|
|
198
|
+
*/
|
|
199
|
+
_timezone = null;
|
|
200
|
+
/**
|
|
201
|
+
* Cron expression parser (mutually exclusive with interval config)
|
|
202
|
+
*/
|
|
203
|
+
_cronParser = null;
|
|
204
|
+
/**
|
|
205
|
+
* Promise resolver for completion waiting
|
|
206
|
+
*/
|
|
207
|
+
_completionResolver = null;
|
|
208
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
209
|
+
// Public Properties
|
|
210
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
211
|
+
/**
|
|
212
|
+
* Next scheduled execution time
|
|
213
|
+
*/
|
|
214
|
+
nextRun = null;
|
|
215
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
216
|
+
// Public Getters
|
|
217
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
218
|
+
/**
|
|
219
|
+
* Returns true if the job is currently executing
|
|
220
|
+
*/
|
|
221
|
+
get isRunning() {
|
|
222
|
+
return this._isRunning;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Returns the last execution timestamp
|
|
226
|
+
*/
|
|
227
|
+
get lastRun() {
|
|
228
|
+
return this._lastRun;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Returns the current interval configuration (readonly)
|
|
232
|
+
*/
|
|
233
|
+
get intervals() {
|
|
234
|
+
return this._intervals;
|
|
235
|
+
}
|
|
236
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
237
|
+
// Interval Configuration Methods (Fluent API)
|
|
238
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
239
|
+
/**
|
|
240
|
+
* Set a custom interval for job execution
|
|
241
|
+
*
|
|
242
|
+
* @param value - Number of time units
|
|
243
|
+
* @param timeType - Type of time unit
|
|
244
|
+
* @returns this for chaining
|
|
245
|
+
*
|
|
246
|
+
* @example
|
|
247
|
+
* ```typescript
|
|
248
|
+
* job.every(5, "minute"); // Run every 5 minutes
|
|
249
|
+
* job.every(2, "hour"); // Run every 2 hours
|
|
250
|
+
* ```
|
|
251
|
+
*/
|
|
252
|
+
every(value, timeType) {
|
|
253
|
+
this._intervals.every = { type: timeType, value };
|
|
254
|
+
return this;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Run job every second (use with caution - high frequency)
|
|
258
|
+
*/
|
|
259
|
+
everySecond() {
|
|
260
|
+
return this.every(1, "second");
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Run job every specified number of seconds
|
|
264
|
+
*/
|
|
265
|
+
everySeconds(seconds) {
|
|
266
|
+
return this.every(seconds, "second");
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Run job every minute
|
|
270
|
+
*/
|
|
271
|
+
everyMinute() {
|
|
272
|
+
return this.every(1, "minute");
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Run job every specified number of minutes
|
|
276
|
+
*/
|
|
277
|
+
everyMinutes(minutes) {
|
|
278
|
+
return this.every(minutes, "minute");
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Run job every hour
|
|
282
|
+
*/
|
|
283
|
+
everyHour() {
|
|
284
|
+
return this.every(1, "hour");
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Run job every specified number of hours
|
|
288
|
+
*/
|
|
289
|
+
everyHours(hours) {
|
|
290
|
+
return this.every(hours, "hour");
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Run job every day at midnight
|
|
294
|
+
*/
|
|
295
|
+
everyDay() {
|
|
296
|
+
return this.every(1, "day");
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Alias for everyDay()
|
|
300
|
+
*/
|
|
301
|
+
daily() {
|
|
302
|
+
return this.everyDay();
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Run job twice a day (every 12 hours)
|
|
306
|
+
*/
|
|
307
|
+
twiceDaily() {
|
|
308
|
+
return this.every(12, "hour");
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Run job every week
|
|
312
|
+
*/
|
|
313
|
+
everyWeek() {
|
|
314
|
+
return this.every(1, "week");
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Alias for everyWeek()
|
|
318
|
+
*/
|
|
319
|
+
weekly() {
|
|
320
|
+
return this.everyWeek();
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Run job every month
|
|
324
|
+
*/
|
|
325
|
+
everyMonth() {
|
|
326
|
+
return this.every(1, "month");
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Alias for everyMonth()
|
|
330
|
+
*/
|
|
331
|
+
monthly() {
|
|
332
|
+
return this.everyMonth();
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Run job every year
|
|
336
|
+
*/
|
|
337
|
+
everyYear() {
|
|
338
|
+
return this.every(1, "year");
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Alias for everyYear()
|
|
342
|
+
*/
|
|
343
|
+
yearly() {
|
|
344
|
+
return this.everyYear();
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Alias for everyMinute() - job runs continuously every minute
|
|
348
|
+
*/
|
|
349
|
+
always() {
|
|
350
|
+
return this.everyMinute();
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Schedule job using a cron expression
|
|
354
|
+
*
|
|
355
|
+
* Supports standard 5-field cron syntax:
|
|
356
|
+
* ```
|
|
357
|
+
* ┌───────────── minute (0-59)
|
|
358
|
+
* │ ┌───────────── hour (0-23)
|
|
359
|
+
* │ │ ┌───────────── day of month (1-31)
|
|
360
|
+
* │ │ │ ┌───────────── month (1-12)
|
|
361
|
+
* │ │ │ │ ┌───────────── day of week (0-6, Sunday = 0)
|
|
362
|
+
* │ │ │ │ │
|
|
363
|
+
* * * * * *
|
|
364
|
+
* ```
|
|
365
|
+
*
|
|
366
|
+
* Supports:
|
|
367
|
+
* - '*' - any value
|
|
368
|
+
* - '5' - specific value
|
|
369
|
+
* - '1,3,5' - list of values
|
|
370
|
+
* - '1-5' - range of values
|
|
371
|
+
* - 'x/5' - step values (every 5)
|
|
372
|
+
* - '1-10/2' - range with step
|
|
373
|
+
*
|
|
374
|
+
* @param expression - Standard 5-field cron expression
|
|
375
|
+
* @returns this for chaining
|
|
376
|
+
*
|
|
377
|
+
* @example
|
|
378
|
+
* ```typescript
|
|
379
|
+
* job.cron("0 9 * * 1-5"); // 9 AM weekdays
|
|
380
|
+
* job.cron("x/5 * * * *"); // Every 5 minutes
|
|
381
|
+
* job.cron("0 0 1 * *"); // First day of month at midnight
|
|
382
|
+
* job.cron("0 x/2 * * *"); // Every 2 hours
|
|
383
|
+
* ```
|
|
384
|
+
*/
|
|
385
|
+
cron(expression) {
|
|
386
|
+
this._cronParser = new CronParser(expression);
|
|
387
|
+
this._intervals = {};
|
|
388
|
+
return this;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Get the cron expression if one is set
|
|
392
|
+
*/
|
|
393
|
+
get cronExpression() {
|
|
394
|
+
return this._cronParser?.expression ?? null;
|
|
395
|
+
}
|
|
396
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
397
|
+
// Day & Time Configuration Methods
|
|
398
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
399
|
+
/**
|
|
400
|
+
* Schedule job on a specific day
|
|
401
|
+
*
|
|
402
|
+
* @param day - Day of week (string) or day of month (number 1-31)
|
|
403
|
+
* @returns this for chaining
|
|
404
|
+
*
|
|
405
|
+
* @example
|
|
406
|
+
* ```typescript
|
|
407
|
+
* job.on("monday"); // Run on Mondays
|
|
408
|
+
* job.on(15); // Run on the 15th of each month
|
|
409
|
+
* ```
|
|
410
|
+
*/
|
|
411
|
+
on(day) {
|
|
412
|
+
if (typeof day === "number" && (day < 1 || day > 31)) {
|
|
413
|
+
throw new Error("Invalid day of the month. Must be between 1 and 31.");
|
|
414
|
+
}
|
|
415
|
+
this._intervals.day = day;
|
|
416
|
+
return this;
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Schedule job at a specific time
|
|
420
|
+
*
|
|
421
|
+
* @param time - Time in HH:mm or HH:mm:ss format
|
|
422
|
+
* @returns this for chaining
|
|
423
|
+
*
|
|
424
|
+
* @example
|
|
425
|
+
* ```typescript
|
|
426
|
+
* job.daily().at("09:00"); // Run daily at 9 AM
|
|
427
|
+
* job.weekly().at("14:30"); // Run weekly at 2:30 PM
|
|
428
|
+
* ```
|
|
429
|
+
*/
|
|
430
|
+
at(time) {
|
|
431
|
+
if (!/^\d{1,2}:\d{2}(:\d{2})?$/.test(time)) {
|
|
432
|
+
throw new Error("Invalid time format. Use HH:mm or HH:mm:ss.");
|
|
433
|
+
}
|
|
434
|
+
this._intervals.time = time;
|
|
435
|
+
return this;
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Run task at the beginning of the specified time period
|
|
439
|
+
*
|
|
440
|
+
* @param type - Time type (day, month, year)
|
|
441
|
+
*/
|
|
442
|
+
beginOf(type) {
|
|
443
|
+
const time = "00:00";
|
|
444
|
+
switch (type) {
|
|
445
|
+
case "day":
|
|
446
|
+
break;
|
|
447
|
+
case "month":
|
|
448
|
+
this.on(1);
|
|
449
|
+
break;
|
|
450
|
+
case "year":
|
|
451
|
+
this.on(1);
|
|
452
|
+
this.every(1, "year");
|
|
453
|
+
break;
|
|
454
|
+
default:
|
|
455
|
+
throw new Error(`Unsupported type for beginOf: ${type}`);
|
|
456
|
+
}
|
|
457
|
+
return this.at(time);
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Run task at the end of the specified time period
|
|
461
|
+
*
|
|
462
|
+
* @param type - Time type (day, month, year)
|
|
463
|
+
*/
|
|
464
|
+
endOf(type) {
|
|
465
|
+
const now = this._now();
|
|
466
|
+
const time = "23:59";
|
|
467
|
+
switch (type) {
|
|
468
|
+
case "day":
|
|
469
|
+
break;
|
|
470
|
+
case "month":
|
|
471
|
+
this.on(now.endOf("month").date());
|
|
472
|
+
break;
|
|
473
|
+
case "year":
|
|
474
|
+
this.on(31);
|
|
475
|
+
this.every(1, "year");
|
|
476
|
+
break;
|
|
477
|
+
default:
|
|
478
|
+
throw new Error(`Unsupported type for endOf: ${type}`);
|
|
479
|
+
}
|
|
480
|
+
return this.at(time);
|
|
481
|
+
}
|
|
482
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
483
|
+
// Timezone Configuration
|
|
484
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
485
|
+
/**
|
|
486
|
+
* Set the timezone for this job's scheduling
|
|
487
|
+
*
|
|
488
|
+
* @param tz - IANA timezone string (e.g., "America/New_York", "Europe/London")
|
|
489
|
+
* @returns this for chaining
|
|
490
|
+
*
|
|
491
|
+
* @example
|
|
492
|
+
* ```typescript
|
|
493
|
+
* job.daily().at("09:00").inTimezone("America/New_York");
|
|
494
|
+
* ```
|
|
495
|
+
*/
|
|
496
|
+
inTimezone(tz) {
|
|
497
|
+
this._timezone = tz;
|
|
498
|
+
return this;
|
|
499
|
+
}
|
|
500
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
501
|
+
// Execution Options
|
|
502
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
503
|
+
/**
|
|
504
|
+
* Prevent overlapping executions of this job
|
|
505
|
+
*
|
|
506
|
+
* When enabled, if the job is already running when it's scheduled to run again,
|
|
507
|
+
* the new execution will be skipped.
|
|
508
|
+
*
|
|
509
|
+
* @param skip - Whether to skip if already running (default: true)
|
|
510
|
+
* @returns this for chaining
|
|
511
|
+
*/
|
|
512
|
+
preventOverlap(skip = true) {
|
|
513
|
+
this._skipIfRunning = skip;
|
|
514
|
+
return this;
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Configure automatic retry on failure
|
|
518
|
+
*
|
|
519
|
+
* @param maxRetries - Maximum number of retry attempts
|
|
520
|
+
* @param delay - Delay between retries in milliseconds
|
|
521
|
+
* @param backoffMultiplier - Optional multiplier for exponential backoff
|
|
522
|
+
* @returns this for chaining
|
|
523
|
+
*
|
|
524
|
+
* @example
|
|
525
|
+
* ```typescript
|
|
526
|
+
* job.retry(3, 1000); // Retry 3 times with 1s delay
|
|
527
|
+
* job.retry(5, 1000, 2); // Exponential backoff: 1s, 2s, 4s, 8s, 16s
|
|
528
|
+
* ```
|
|
529
|
+
*/
|
|
530
|
+
retry(maxRetries, delay = 1e3, backoffMultiplier) {
|
|
531
|
+
this._retryConfig = {
|
|
532
|
+
maxRetries,
|
|
533
|
+
delay,
|
|
534
|
+
backoffMultiplier
|
|
535
|
+
};
|
|
536
|
+
return this;
|
|
537
|
+
}
|
|
538
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
539
|
+
// Execution Control
|
|
540
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
541
|
+
/**
|
|
542
|
+
* Terminate the job and clear all scheduling data
|
|
543
|
+
*/
|
|
544
|
+
terminate() {
|
|
545
|
+
this._intervals = {};
|
|
546
|
+
this.nextRun = null;
|
|
547
|
+
this._lastRun = null;
|
|
548
|
+
this._isRunning = false;
|
|
549
|
+
return this;
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Prepare the job by calculating the next run time
|
|
553
|
+
* Called by the scheduler when starting
|
|
554
|
+
*/
|
|
555
|
+
prepare() {
|
|
556
|
+
this._determineNextRun();
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Determine if the job should run now
|
|
560
|
+
*
|
|
561
|
+
* @returns true if the job should execute
|
|
562
|
+
*/
|
|
563
|
+
shouldRun() {
|
|
564
|
+
if (this._skipIfRunning && this._isRunning) {
|
|
565
|
+
return false;
|
|
566
|
+
}
|
|
567
|
+
return this.nextRun !== null && this._now().isAfter(this.nextRun);
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Execute the job
|
|
571
|
+
*
|
|
572
|
+
* @returns Promise resolving to the job result
|
|
573
|
+
*/
|
|
574
|
+
async run() {
|
|
575
|
+
const startTime = Date.now();
|
|
576
|
+
this._isRunning = true;
|
|
577
|
+
try {
|
|
578
|
+
const result = await this._executeWithRetry();
|
|
579
|
+
this._lastRun = this._now();
|
|
580
|
+
this._determineNextRun();
|
|
581
|
+
return {
|
|
582
|
+
success: true,
|
|
583
|
+
duration: Date.now() - startTime,
|
|
584
|
+
retries: result.retries || 0
|
|
585
|
+
};
|
|
586
|
+
} catch (error) {
|
|
587
|
+
return {
|
|
588
|
+
success: false,
|
|
589
|
+
duration: Date.now() - startTime,
|
|
590
|
+
error,
|
|
591
|
+
retries: this._retryConfig?.maxRetries ?? 0
|
|
592
|
+
};
|
|
593
|
+
} finally {
|
|
594
|
+
this._isRunning = false;
|
|
595
|
+
if (this._completionResolver) {
|
|
596
|
+
this._completionResolver();
|
|
597
|
+
this._completionResolver = null;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* Wait for the job to complete
|
|
603
|
+
* Useful for graceful shutdown
|
|
604
|
+
*
|
|
605
|
+
* @returns Promise that resolves when the job completes
|
|
606
|
+
*/
|
|
607
|
+
waitForCompletion() {
|
|
608
|
+
if (!this._isRunning) {
|
|
609
|
+
return Promise.resolve();
|
|
610
|
+
}
|
|
611
|
+
return new Promise((resolve) => {
|
|
612
|
+
this._completionResolver = resolve;
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
616
|
+
// Private Methods
|
|
617
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
618
|
+
/**
|
|
619
|
+
* Get current time, respecting timezone if set
|
|
620
|
+
*/
|
|
621
|
+
_now() {
|
|
622
|
+
return this._timezone ? dayjs2().tz(this._timezone) : dayjs2();
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Execute the callback with retry logic
|
|
626
|
+
*/
|
|
627
|
+
async _executeWithRetry() {
|
|
628
|
+
let lastError;
|
|
629
|
+
let attempts = 0;
|
|
630
|
+
const maxAttempts = (this._retryConfig?.maxRetries ?? 0) + 1;
|
|
631
|
+
while (attempts < maxAttempts) {
|
|
632
|
+
try {
|
|
633
|
+
await this._callback(this);
|
|
634
|
+
return { retries: attempts };
|
|
635
|
+
} catch (error) {
|
|
636
|
+
lastError = error;
|
|
637
|
+
attempts++;
|
|
638
|
+
if (attempts < maxAttempts && this._retryConfig) {
|
|
639
|
+
const delay = this._calculateRetryDelay(attempts);
|
|
640
|
+
await this._sleep(delay);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
throw lastError;
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Calculate retry delay with optional exponential backoff
|
|
648
|
+
*/
|
|
649
|
+
_calculateRetryDelay(attempt) {
|
|
650
|
+
if (!this._retryConfig) return 0;
|
|
651
|
+
const { delay, backoffMultiplier } = this._retryConfig;
|
|
652
|
+
if (backoffMultiplier) {
|
|
653
|
+
return delay * Math.pow(backoffMultiplier, attempt - 1);
|
|
654
|
+
}
|
|
655
|
+
return delay;
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Sleep for specified milliseconds
|
|
659
|
+
*/
|
|
660
|
+
_sleep(ms) {
|
|
661
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Calculate the next run time based on interval or cron configuration
|
|
665
|
+
*/
|
|
666
|
+
_determineNextRun() {
|
|
667
|
+
if (this._cronParser) {
|
|
668
|
+
const now = this._now();
|
|
669
|
+
this.nextRun = this._cronParser.nextRun(now);
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
let date = this._lastRun ? this._lastRun.add(1, "second") : this._now();
|
|
673
|
+
if (this._intervals.every?.value && this._intervals.every?.type) {
|
|
674
|
+
date = date.add(this._intervals.every.value, this._intervals.every.type);
|
|
675
|
+
}
|
|
676
|
+
if (this._intervals.day !== void 0) {
|
|
677
|
+
if (typeof this._intervals.day === "number") {
|
|
678
|
+
date = date.date(this._intervals.day);
|
|
679
|
+
} else {
|
|
680
|
+
const targetDay = DAYS_OF_WEEK.indexOf(this._intervals.day);
|
|
681
|
+
if (targetDay !== -1) {
|
|
682
|
+
date = date.day(targetDay);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
if (this._intervals.time) {
|
|
687
|
+
const parts = this._intervals.time.split(":").map(Number);
|
|
688
|
+
const [hour, minute, second = 0] = parts;
|
|
689
|
+
date = date.hour(hour).minute(minute).second(second).millisecond(0);
|
|
690
|
+
}
|
|
691
|
+
while (date.isBefore(this._now())) {
|
|
692
|
+
if (this._intervals.every?.value && this._intervals.every?.type) {
|
|
693
|
+
date = date.add(this._intervals.every.value, this._intervals.every.type);
|
|
694
|
+
} else {
|
|
695
|
+
date = date.add(1, "day");
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
this.nextRun = date;
|
|
699
|
+
}
|
|
700
|
+
};
|
|
701
|
+
function job(name, callback) {
|
|
702
|
+
return new Job(name, callback);
|
|
703
|
+
}
|
|
704
|
+
var Scheduler = class extends EventEmitter {
|
|
705
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
706
|
+
// Private Properties
|
|
707
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
708
|
+
/**
|
|
709
|
+
* List of registered jobs
|
|
710
|
+
*/
|
|
711
|
+
_jobs = [];
|
|
712
|
+
/**
|
|
713
|
+
* Reference to the current timeout for stopping
|
|
714
|
+
*/
|
|
715
|
+
_timeoutId = null;
|
|
716
|
+
/**
|
|
717
|
+
* Tick interval in milliseconds (how often to check for due jobs)
|
|
718
|
+
*/
|
|
719
|
+
_tickInterval = 1e3;
|
|
720
|
+
/**
|
|
721
|
+
* Whether to run due jobs in parallel
|
|
722
|
+
*/
|
|
723
|
+
_runInParallel = false;
|
|
724
|
+
/**
|
|
725
|
+
* Maximum concurrent jobs when running in parallel
|
|
726
|
+
*/
|
|
727
|
+
_maxConcurrency = 10;
|
|
728
|
+
/**
|
|
729
|
+
* Flag indicating scheduler is shutting down
|
|
730
|
+
*/
|
|
731
|
+
_isShuttingDown = false;
|
|
732
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
733
|
+
// Public Getters
|
|
734
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
735
|
+
/**
|
|
736
|
+
* Returns true if the scheduler is currently running
|
|
737
|
+
*/
|
|
738
|
+
get isRunning() {
|
|
739
|
+
return this._timeoutId !== null;
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* Returns the number of registered jobs
|
|
743
|
+
*/
|
|
744
|
+
get jobCount() {
|
|
745
|
+
return this._jobs.length;
|
|
746
|
+
}
|
|
747
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
748
|
+
// Configuration Methods (Fluent API)
|
|
749
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
750
|
+
/**
|
|
751
|
+
* Add a job to the scheduler
|
|
752
|
+
*
|
|
753
|
+
* @param job - Job instance to schedule
|
|
754
|
+
* @returns this for chaining
|
|
755
|
+
*/
|
|
756
|
+
addJob(job2) {
|
|
757
|
+
this._jobs.push(job2);
|
|
758
|
+
return this;
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* Alias to create a new job directly and store it
|
|
762
|
+
*/
|
|
763
|
+
newJob(name, jobCallback) {
|
|
764
|
+
const job2 = new Job(name, jobCallback);
|
|
765
|
+
this.addJob(job2);
|
|
766
|
+
return job2;
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Add multiple jobs to the scheduler
|
|
770
|
+
*
|
|
771
|
+
* @param jobs - Array of Job instances
|
|
772
|
+
* @returns this for chaining
|
|
773
|
+
*/
|
|
774
|
+
addJobs(jobs) {
|
|
775
|
+
this._jobs.push(...jobs);
|
|
776
|
+
return this;
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Remove a job from the scheduler by name
|
|
780
|
+
*
|
|
781
|
+
* @param jobName - Name of the job to remove
|
|
782
|
+
* @returns true if job was found and removed
|
|
783
|
+
*/
|
|
784
|
+
removeJob(jobName) {
|
|
785
|
+
const index = this._jobs.findIndex((j) => j.name === jobName);
|
|
786
|
+
if (index !== -1) {
|
|
787
|
+
this._jobs.splice(index, 1);
|
|
788
|
+
return true;
|
|
789
|
+
}
|
|
790
|
+
return false;
|
|
791
|
+
}
|
|
792
|
+
/**
|
|
793
|
+
* Get a job by name
|
|
794
|
+
*
|
|
795
|
+
* @param jobName - Name of the job to find
|
|
796
|
+
* @returns Job instance or undefined
|
|
797
|
+
*/
|
|
798
|
+
getJob(jobName) {
|
|
799
|
+
return this._jobs.find((j) => j.name === jobName);
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Get all registered jobs
|
|
803
|
+
*
|
|
804
|
+
* @returns Array of registered jobs (readonly)
|
|
805
|
+
*/
|
|
806
|
+
list() {
|
|
807
|
+
return this._jobs;
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Set the tick interval (how often to check for due jobs)
|
|
811
|
+
*
|
|
812
|
+
* @param ms - Interval in milliseconds (minimum 100ms)
|
|
813
|
+
* @returns this for chaining
|
|
814
|
+
*/
|
|
815
|
+
runEvery(ms) {
|
|
816
|
+
if (ms < 100) {
|
|
817
|
+
throw new Error("Tick interval must be at least 100ms");
|
|
818
|
+
}
|
|
819
|
+
this._tickInterval = ms;
|
|
820
|
+
return this;
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Configure whether jobs should run in parallel
|
|
824
|
+
*
|
|
825
|
+
* @param parallel - Enable parallel execution
|
|
826
|
+
* @param maxConcurrency - Maximum concurrent jobs (default: 10)
|
|
827
|
+
* @returns this for chaining
|
|
828
|
+
*/
|
|
829
|
+
runInParallel(parallel, maxConcurrency = 10) {
|
|
830
|
+
this._runInParallel = parallel;
|
|
831
|
+
this._maxConcurrency = maxConcurrency;
|
|
832
|
+
return this;
|
|
833
|
+
}
|
|
834
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
835
|
+
// Lifecycle Methods
|
|
836
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
837
|
+
/**
|
|
838
|
+
* Start the scheduler
|
|
839
|
+
*
|
|
840
|
+
* @throws Error if scheduler is already running
|
|
841
|
+
*/
|
|
842
|
+
start() {
|
|
843
|
+
if (this.isRunning) {
|
|
844
|
+
throw new Error("Scheduler is already running.");
|
|
845
|
+
}
|
|
846
|
+
if (this._jobs.length === 0) {
|
|
847
|
+
throw new Error("Cannot start scheduler with no jobs.");
|
|
848
|
+
}
|
|
849
|
+
for (const job2 of this._jobs) {
|
|
850
|
+
job2.prepare();
|
|
851
|
+
}
|
|
852
|
+
this._isShuttingDown = false;
|
|
853
|
+
this._scheduleTick();
|
|
854
|
+
this.emit("scheduler:started");
|
|
855
|
+
}
|
|
856
|
+
/**
|
|
857
|
+
* Stop the scheduler immediately
|
|
858
|
+
*
|
|
859
|
+
* Note: This does not wait for running jobs to complete.
|
|
860
|
+
* Use shutdown() for graceful termination.
|
|
861
|
+
*/
|
|
862
|
+
stop() {
|
|
863
|
+
if (this._timeoutId) {
|
|
864
|
+
clearTimeout(this._timeoutId);
|
|
865
|
+
this._timeoutId = null;
|
|
866
|
+
}
|
|
867
|
+
this.emit("scheduler:stopped");
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Gracefully shutdown the scheduler
|
|
871
|
+
*
|
|
872
|
+
* Stops scheduling new jobs and waits for currently running jobs to complete.
|
|
873
|
+
*
|
|
874
|
+
* @param timeout - Maximum time to wait for jobs (default: 30000ms)
|
|
875
|
+
* @returns Promise that resolves when shutdown is complete
|
|
876
|
+
*/
|
|
877
|
+
async shutdown(timeout = 3e4) {
|
|
878
|
+
this._isShuttingDown = true;
|
|
879
|
+
this.stop();
|
|
880
|
+
const runningJobs = this._jobs.filter((j) => j.isRunning);
|
|
881
|
+
if (runningJobs.length > 0) {
|
|
882
|
+
await Promise.race([
|
|
883
|
+
Promise.all(runningJobs.map((j) => j.waitForCompletion())),
|
|
884
|
+
new Promise((resolve) => setTimeout(resolve, timeout))
|
|
885
|
+
]);
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
889
|
+
// Private Methods
|
|
890
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
891
|
+
/**
|
|
892
|
+
* Schedule the next tick
|
|
893
|
+
*/
|
|
894
|
+
_scheduleTick() {
|
|
895
|
+
if (this._isShuttingDown) return;
|
|
896
|
+
const startTime = Date.now();
|
|
897
|
+
this._timeoutId = setTimeout(async () => {
|
|
898
|
+
await this._tick();
|
|
899
|
+
const elapsed = Date.now() - startTime;
|
|
900
|
+
Math.max(this._tickInterval - elapsed, 0);
|
|
901
|
+
this._scheduleTick();
|
|
902
|
+
}, this._tickInterval);
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* Execute a scheduler tick - check and run due jobs
|
|
906
|
+
*/
|
|
907
|
+
async _tick() {
|
|
908
|
+
this.emit("scheduler:tick", /* @__PURE__ */ new Date());
|
|
909
|
+
const dueJobs = this._jobs.filter((job2) => {
|
|
910
|
+
if (!job2.shouldRun()) return false;
|
|
911
|
+
if (job2.isRunning) {
|
|
912
|
+
this.emit("job:skip", job2.name, "Job is already running");
|
|
913
|
+
return false;
|
|
914
|
+
}
|
|
915
|
+
return true;
|
|
916
|
+
});
|
|
917
|
+
if (dueJobs.length === 0) return;
|
|
918
|
+
if (this._runInParallel) {
|
|
919
|
+
await this._runJobsInParallel(dueJobs);
|
|
920
|
+
} else {
|
|
921
|
+
await this._runJobsSequentially(dueJobs);
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Run jobs sequentially
|
|
926
|
+
*/
|
|
927
|
+
async _runJobsSequentially(jobs) {
|
|
928
|
+
for (const job2 of jobs) {
|
|
929
|
+
if (this._isShuttingDown) break;
|
|
930
|
+
await this._runJob(job2);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Run jobs in parallel with concurrency limit
|
|
935
|
+
*/
|
|
936
|
+
async _runJobsInParallel(jobs) {
|
|
937
|
+
const batches = [];
|
|
938
|
+
for (let i = 0; i < jobs.length; i += this._maxConcurrency) {
|
|
939
|
+
batches.push(jobs.slice(i, i + this._maxConcurrency));
|
|
940
|
+
}
|
|
941
|
+
for (const batch of batches) {
|
|
942
|
+
if (this._isShuttingDown) break;
|
|
943
|
+
await Promise.allSettled(batch.map((job2) => this._runJob(job2)));
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Run a single job and emit events
|
|
948
|
+
*/
|
|
949
|
+
async _runJob(job2) {
|
|
950
|
+
this.emit("job:start", job2.name);
|
|
951
|
+
const result = await job2.run();
|
|
952
|
+
if (result.success) {
|
|
953
|
+
this.emit("job:complete", job2.name, result);
|
|
954
|
+
} else {
|
|
955
|
+
this.emit("job:error", job2.name, result.error);
|
|
956
|
+
}
|
|
957
|
+
return result;
|
|
958
|
+
}
|
|
959
|
+
};
|
|
960
|
+
var scheduler = new Scheduler();
|
|
961
|
+
|
|
962
|
+
export { CronParser, Job, Scheduler, job, parseCron, scheduler };
|
|
963
|
+
//# sourceMappingURL=index.js.map
|
|
2
964
|
//# sourceMappingURL=index.js.map
|