@cldmv/holdmytask 1.0.0 → 1.1.0
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 +33 -2
- package/dist/hold-my-task.mjs +301 -25
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -12,6 +12,7 @@ A tiny, dependency-free task queue for Node.js that executes tasks with priority
|
|
|
12
12
|
|
|
13
13
|
## ✨ Features
|
|
14
14
|
|
|
15
|
+
- **Smart scheduling** - Dynamic timeout-based scheduling for optimal performance
|
|
15
16
|
- **Priority-based execution** - Higher priority tasks run first
|
|
16
17
|
- **Concurrency control** - Limit simultaneous task execution
|
|
17
18
|
- **Completion delays** - Configurable delays between task completions
|
|
@@ -136,7 +137,8 @@ const queue = new HoldMyTask(options?)
|
|
|
136
137
|
**Options:**
|
|
137
138
|
|
|
138
139
|
- `concurrency` (number, default: 1) - Maximum concurrent tasks
|
|
139
|
-
- `
|
|
140
|
+
- `smartScheduling` (boolean, default: true) - Use dynamic timeout scheduling for better performance
|
|
141
|
+
- `tick` (number, default: 25) - Scheduler tick interval in milliseconds (used when smartScheduling is false)
|
|
140
142
|
- `autoStart` (boolean, default: true) - Whether to start processing immediately
|
|
141
143
|
- `defaultPriority` (number, default: 0) - Default task priority
|
|
142
144
|
- `maxQueue` (number, default: Infinity) - Maximum queued tasks
|
|
@@ -255,7 +257,7 @@ HoldMyTask uses a sophisticated dual-heap scheduling system for optimal performa
|
|
|
255
257
|
|
|
256
258
|
**📊 Scheduling Flow:**
|
|
257
259
|
|
|
258
|
-
```
|
|
260
|
+
```text
|
|
259
261
|
1. New tasks → Pending Heap (ordered by readyAt timestamp)
|
|
260
262
|
2. Scheduler tick → Move ready tasks: Pending → Ready Heap
|
|
261
263
|
3. Execution → Take highest priority from Ready Heap
|
|
@@ -303,6 +305,35 @@ await queue.enqueue(task2, { priority: 10 }); // Runs first
|
|
|
303
305
|
await queue.enqueue(task3, { priority: 5 });
|
|
304
306
|
```
|
|
305
307
|
|
|
308
|
+
### Smart Scheduling
|
|
309
|
+
|
|
310
|
+
By default, HoldMyTask uses intelligent dynamic scheduling that calculates optimal timeout intervals based on when tasks should become ready. This provides significant performance improvements over traditional polling.
|
|
311
|
+
|
|
312
|
+
**Benefits:**
|
|
313
|
+
|
|
314
|
+
- **31x performance improvement** in typical scenarios
|
|
315
|
+
- **Precise timing** - tasks execute exactly when ready
|
|
316
|
+
- **CPU efficient** - no constant polling overhead
|
|
317
|
+
- **Dynamic adaptation** - adjusts to task timing patterns
|
|
318
|
+
|
|
319
|
+
```javascript
|
|
320
|
+
// Smart scheduling enabled by default
|
|
321
|
+
const queue = new HoldMyTask();
|
|
322
|
+
|
|
323
|
+
// Traditional polling mode (for compatibility)
|
|
324
|
+
const legacyQueue = new HoldMyTask({
|
|
325
|
+
smartScheduling: false,
|
|
326
|
+
tick: 25 // polling interval in ms
|
|
327
|
+
});
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
**How it works:**
|
|
331
|
+
|
|
332
|
+
- Calculates the next task ready time
|
|
333
|
+
- Sets a precise timeout for that moment
|
|
334
|
+
- Includes healing mechanism to prevent scheduler stalls
|
|
335
|
+
- Falls back gracefully on complex timing scenarios
|
|
336
|
+
|
|
306
337
|
### Priority Delays - Advanced Timing Control
|
|
307
338
|
|
|
308
339
|
Priority delays create "cool-down" periods after task completion based on the completed task's priority. This helps prevent resource overwhelming, implement rate limiting, and control timing between operations.
|
package/dist/hold-my-task.mjs
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* @Email: <Shinrai@users.noreply.github.com>
|
|
7
7
|
* -----
|
|
8
8
|
* @Last modified by: Nate Hyson <CLDMV> (Shinrai@users.noreply.github.com)
|
|
9
|
-
* @Last modified time: 2025-11-
|
|
9
|
+
* @Last modified time: 2025-11-10 22:14:06 -08:00 (1762841646)
|
|
10
10
|
* -----
|
|
11
11
|
* @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
|
|
12
12
|
*/
|
|
@@ -30,6 +30,9 @@ export class HoldMyTask extends EventEmitter {
|
|
|
30
30
|
* @param {number} [options.defaultPriority=0] - Default priority for tasks (higher numbers = higher priority)
|
|
31
31
|
* @param {number} [options.maxQueue=Infinity] - Maximum number of tasks that can be queued
|
|
32
32
|
* @param {Object} [options.delays={}] - Map of priority levels to delay times in milliseconds between task completions
|
|
33
|
+
* @param {boolean} [options.smartScheduling=true] - Use dynamic timeouts instead of constant polling for better performance
|
|
34
|
+
* @param {number} [options.tick=25] - Polling interval in milliseconds when smartScheduling is disabled
|
|
35
|
+
* @param {number} [options.healingInterval=5000] - Self-healing check interval in milliseconds (smart scheduling only)
|
|
33
36
|
* @example
|
|
34
37
|
* const queue = new HoldMyTask({
|
|
35
38
|
* concurrency: 2,
|
|
@@ -37,6 +40,13 @@ export class HoldMyTask extends EventEmitter {
|
|
|
37
40
|
* defaultPriority: 1,
|
|
38
41
|
* delays: { 0: 1000, 1: 500 }
|
|
39
42
|
* });
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* // Use traditional polling instead of smart scheduling
|
|
46
|
+
* const legacyQueue = new HoldMyTask({
|
|
47
|
+
* smartScheduling: false,
|
|
48
|
+
* tick: 50
|
|
49
|
+
* });
|
|
40
50
|
*/
|
|
41
51
|
constructor(options = {}) {
|
|
42
52
|
super();
|
|
@@ -47,6 +57,8 @@ export class HoldMyTask extends EventEmitter {
|
|
|
47
57
|
defaultPriority: 0,
|
|
48
58
|
maxQueue: Infinity,
|
|
49
59
|
delays: {}, // priority -> delay in ms between tasks of that priority
|
|
60
|
+
smartScheduling: true, // Use smart timeouts instead of polling by default
|
|
61
|
+
healingInterval: 5000, // Self-healing check interval (smart scheduling only)
|
|
50
62
|
...options
|
|
51
63
|
};
|
|
52
64
|
|
|
@@ -67,6 +79,14 @@ export class HoldMyTask extends EventEmitter {
|
|
|
67
79
|
this.lastCompletedPriority = null;
|
|
68
80
|
this.nextAvailableTime = 0; // For delays after task completion
|
|
69
81
|
|
|
82
|
+
// Smart scheduling state (used when smartScheduling is enabled)
|
|
83
|
+
this.schedulerTimeout = null;
|
|
84
|
+
this.healingInterval = null;
|
|
85
|
+
this.lastSchedulerRun = 0;
|
|
86
|
+
|
|
87
|
+
// Traditional polling state (used when smartScheduling is disabled)
|
|
88
|
+
this.intervalId = null;
|
|
89
|
+
|
|
70
90
|
if (this.options.autoStart) {
|
|
71
91
|
this.resume();
|
|
72
92
|
}
|
|
@@ -80,7 +100,8 @@ export class HoldMyTask extends EventEmitter {
|
|
|
80
100
|
* @param {number} [options.priority] - Task priority (higher numbers run first)
|
|
81
101
|
* @param {number} [options.timestamp] - When the task should be ready to run (milliseconds since epoch)
|
|
82
102
|
* @param {AbortSignal} [options.signal] - AbortSignal to cancel the task
|
|
83
|
-
* @param {number} [options.timeout] - Task timeout in milliseconds
|
|
103
|
+
* @param {number} [options.timeout] - Task timeout in milliseconds (for execution time limit)
|
|
104
|
+
* @param {number} [options.expire] - Task expiration timestamp or milliseconds from now (for queue waiting time limit)
|
|
84
105
|
* @param {number} [options.delay] - Delay after task completion before next task of same priority
|
|
85
106
|
* @param {boolean} [options.bypassDelay] - If true, skip any active delay period and start immediately
|
|
86
107
|
* @param {*} [options.metadata] - Arbitrary metadata to attach to the task
|
|
@@ -97,7 +118,7 @@ export class HoldMyTask extends EventEmitter {
|
|
|
97
118
|
* });
|
|
98
119
|
*
|
|
99
120
|
* // With options
|
|
100
|
-
* const task = queue.enqueue(myTask, { priority: 5, timeout: 30000 });
|
|
121
|
+
* const task = queue.enqueue(myTask, { priority: 5, timeout: 30000, expire: 10000 });
|
|
101
122
|
*
|
|
102
123
|
* // Bypass current delay for urgent task
|
|
103
124
|
* const urgent = queue.enqueue(urgentTask, { priority: 10, bypassDelay: true });
|
|
@@ -128,12 +149,25 @@ export class HoldMyTask extends EventEmitter {
|
|
|
128
149
|
const now = this.now();
|
|
129
150
|
const readyAt = finalOptions.timestamp ?? now;
|
|
130
151
|
|
|
152
|
+
// Calculate expiration timestamp
|
|
153
|
+
let expireAt = null;
|
|
154
|
+
if (finalOptions.expire !== undefined) {
|
|
155
|
+
// If expire > current timestamp, treat as absolute timestamp
|
|
156
|
+
// If expire <= current timestamp, treat as milliseconds from now
|
|
157
|
+
if (finalOptions.expire > now) {
|
|
158
|
+
expireAt = finalOptions.expire;
|
|
159
|
+
} else {
|
|
160
|
+
expireAt = now + finalOptions.expire;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
131
164
|
const item = {
|
|
132
165
|
id,
|
|
133
166
|
task,
|
|
134
167
|
callback,
|
|
135
168
|
priority: finalOptions.priority ?? this.options.defaultPriority,
|
|
136
169
|
readyAt,
|
|
170
|
+
expireAt,
|
|
137
171
|
enqueueSeq: this.enqueueSeq++,
|
|
138
172
|
status: "pending",
|
|
139
173
|
signal: finalOptions.signal,
|
|
@@ -148,17 +182,20 @@ export class HoldMyTask extends EventEmitter {
|
|
|
148
182
|
|
|
149
183
|
// Check if signal is already aborted
|
|
150
184
|
if (finalOptions.signal?.aborted) {
|
|
151
|
-
this.cancelTask(id, "
|
|
152
|
-
} else if (
|
|
153
|
-
// For callback API, the queue handles signal abortion
|
|
154
|
-
finalOptions.signal
|
|
155
|
-
this.cancelTask(id, "
|
|
185
|
+
this.cancelTask(id, "Task was aborted");
|
|
186
|
+
} else if (finalOptions.signal) {
|
|
187
|
+
// For both callback and promise API, the queue handles signal abortion
|
|
188
|
+
finalOptions.signal.addEventListener("abort", () => {
|
|
189
|
+
this.cancelTask(id, "Task was aborted");
|
|
156
190
|
});
|
|
157
191
|
}
|
|
158
|
-
// For promise API, assume the task handles the signal itself
|
|
159
192
|
|
|
160
193
|
if (this.isActive) {
|
|
161
|
-
this.
|
|
194
|
+
if (this.options.smartScheduling) {
|
|
195
|
+
this.scheduleSmartTimeout();
|
|
196
|
+
} else {
|
|
197
|
+
this.scheduleNextTick();
|
|
198
|
+
}
|
|
162
199
|
}
|
|
163
200
|
|
|
164
201
|
const tasks = this.tasks; // Capture reference
|
|
@@ -237,7 +274,11 @@ export class HoldMyTask extends EventEmitter {
|
|
|
237
274
|
*/
|
|
238
275
|
pause() {
|
|
239
276
|
this.isActive = false;
|
|
240
|
-
this.
|
|
277
|
+
if (this.options.smartScheduling) {
|
|
278
|
+
this.clearSchedulerTimers();
|
|
279
|
+
} else {
|
|
280
|
+
this.clearTimers();
|
|
281
|
+
}
|
|
241
282
|
}
|
|
242
283
|
|
|
243
284
|
/**
|
|
@@ -250,11 +291,25 @@ export class HoldMyTask extends EventEmitter {
|
|
|
250
291
|
resume() {
|
|
251
292
|
if (this.destroyed) return;
|
|
252
293
|
this.isActive = true;
|
|
253
|
-
|
|
254
|
-
if (this.
|
|
255
|
-
|
|
294
|
+
|
|
295
|
+
if (this.options.smartScheduling) {
|
|
296
|
+
// Start healing interval for smart scheduling
|
|
297
|
+
this.startHealingInterval();
|
|
298
|
+
|
|
299
|
+
// If there are pending tasks, run scheduler immediately
|
|
300
|
+
if (this.pendingHeap.size() > 0 || this.readyHeap.size() > 0) {
|
|
301
|
+
this.runScheduler();
|
|
302
|
+
} else {
|
|
303
|
+
this.scheduleSmartTimeout();
|
|
304
|
+
}
|
|
305
|
+
} else {
|
|
306
|
+
// Traditional polling mode
|
|
307
|
+
// If there are pending tasks, run scheduler immediately
|
|
308
|
+
if (this.pendingHeap.size() > 0 || this.readyHeap.size() > 0) {
|
|
309
|
+
this.schedulerTick();
|
|
310
|
+
}
|
|
311
|
+
this.scheduleNextTick();
|
|
256
312
|
}
|
|
257
|
-
this.scheduleNextTick();
|
|
258
313
|
}
|
|
259
314
|
|
|
260
315
|
/**
|
|
@@ -286,11 +341,20 @@ export class HoldMyTask extends EventEmitter {
|
|
|
286
341
|
return a.enqueueSeq - b.enqueueSeq;
|
|
287
342
|
});
|
|
288
343
|
this.tasks.clear();
|
|
344
|
+
|
|
345
|
+
// Reschedule since we may have no work
|
|
346
|
+
if (this.isActive) {
|
|
347
|
+
if (this.options.smartScheduling) {
|
|
348
|
+
this.scheduleSmartTimeout();
|
|
349
|
+
} else {
|
|
350
|
+
// For traditional polling, no need to reschedule as interval will continue
|
|
351
|
+
}
|
|
352
|
+
}
|
|
289
353
|
}
|
|
290
354
|
|
|
291
355
|
/**
|
|
292
|
-
* Returns the
|
|
293
|
-
* @returns {number}
|
|
356
|
+
* Returns the number of tasks in the queue.
|
|
357
|
+
* @returns {number} Number of tasks in the queue
|
|
294
358
|
* @example
|
|
295
359
|
* const totalTasks = queue.size(); // 5
|
|
296
360
|
*/
|
|
@@ -298,6 +362,16 @@ export class HoldMyTask extends EventEmitter {
|
|
|
298
362
|
return this.tasks.size;
|
|
299
363
|
}
|
|
300
364
|
|
|
365
|
+
/**
|
|
366
|
+
* Returns the number of tasks in the queue (alias for size()).
|
|
367
|
+
* @returns {number} Number of tasks in the queue
|
|
368
|
+
* @example
|
|
369
|
+
* const totalTasks = queue.length(); // 5
|
|
370
|
+
*/
|
|
371
|
+
length() {
|
|
372
|
+
return this.tasks.size;
|
|
373
|
+
}
|
|
374
|
+
|
|
301
375
|
/**
|
|
302
376
|
* Returns the number of currently running tasks.
|
|
303
377
|
* @returns {number} Number of running tasks
|
|
@@ -375,13 +449,18 @@ export class HoldMyTask extends EventEmitter {
|
|
|
375
449
|
schedulerTick() {
|
|
376
450
|
const now = this.now();
|
|
377
451
|
|
|
378
|
-
// Move ready tasks from pending to ready heap
|
|
452
|
+
// Move ready tasks from pending to ready heap, checking for expiration
|
|
379
453
|
let nextPending = this.pendingHeap.peek();
|
|
380
454
|
while (nextPending && nextPending.readyAt <= now) {
|
|
381
455
|
const task = this.pendingHeap.pop();
|
|
382
456
|
if (task && task.status === "pending") {
|
|
383
|
-
task
|
|
384
|
-
|
|
457
|
+
// Check if task has expired before making it ready
|
|
458
|
+
if (task.expireAt && now >= task.expireAt) {
|
|
459
|
+
this.expireTask(task);
|
|
460
|
+
} else {
|
|
461
|
+
task.status = "ready";
|
|
462
|
+
this.readyHeap.push(task);
|
|
463
|
+
}
|
|
385
464
|
}
|
|
386
465
|
nextPending = this.pendingHeap.peek();
|
|
387
466
|
}
|
|
@@ -396,6 +475,13 @@ export class HoldMyTask extends EventEmitter {
|
|
|
396
475
|
const task = this.readyHeap.peek();
|
|
397
476
|
if (!task) break;
|
|
398
477
|
|
|
478
|
+
// Check if task has expired before starting it
|
|
479
|
+
if (task.expireAt && currentTime >= task.expireAt) {
|
|
480
|
+
this.readyHeap.pop(); // Remove expired task from heap
|
|
481
|
+
this.expireTask(task);
|
|
482
|
+
continue; // Check next task
|
|
483
|
+
}
|
|
484
|
+
|
|
399
485
|
const canStart = task.bypassDelay || !delayActive;
|
|
400
486
|
|
|
401
487
|
if (canStart) {
|
|
@@ -407,11 +493,27 @@ export class HoldMyTask extends EventEmitter {
|
|
|
407
493
|
let foundBypassTask = false;
|
|
408
494
|
|
|
409
495
|
for (let i = 0; i < heapArray.length; i++) {
|
|
410
|
-
|
|
496
|
+
const bypassTask = heapArray[i];
|
|
497
|
+
|
|
498
|
+
// Check if bypass task has expired
|
|
499
|
+
if (bypassTask.expireAt && currentTime >= bypassTask.expireAt) {
|
|
500
|
+
// Remove expired task and continue searching
|
|
501
|
+
const remainingTasks = heapArray.filter((t) => t.id !== bypassTask.id);
|
|
502
|
+
this.readyHeap.heap = [];
|
|
503
|
+
for (const t of remainingTasks) {
|
|
504
|
+
this.readyHeap.push(t);
|
|
505
|
+
}
|
|
506
|
+
this.expireTask(bypassTask);
|
|
507
|
+
// Update heapArray for next iteration
|
|
508
|
+
heapArray.splice(i, 1);
|
|
509
|
+
i--; // Adjust index since we removed an item
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
if (bypassTask.bypassDelay) {
|
|
411
514
|
foundBypassTask = true;
|
|
412
515
|
// Remove the bypass task from heap and start it
|
|
413
516
|
// We need to rebuild the heap without this task
|
|
414
|
-
const bypassTask = heapArray[i];
|
|
415
517
|
const remainingTasks = heapArray.filter((t) => t.id !== bypassTask.id);
|
|
416
518
|
this.readyHeap.heap = [];
|
|
417
519
|
for (const t of remainingTasks) {
|
|
@@ -431,11 +533,46 @@ export class HoldMyTask extends EventEmitter {
|
|
|
431
533
|
}
|
|
432
534
|
|
|
433
535
|
// Schedule next tick if there are pending tasks or tasks that might become available
|
|
434
|
-
|
|
536
|
+
// Note: For smart scheduling, this is handled by runScheduler calling scheduleSmartTimeout
|
|
537
|
+
if (!this.options.smartScheduling && (this.pendingHeap.size() > 0 || this.readyHeap.size() > 0 || hasWaitingTasks)) {
|
|
435
538
|
this.scheduleNextTick();
|
|
436
539
|
}
|
|
437
540
|
}
|
|
438
541
|
|
|
542
|
+
/**
|
|
543
|
+
* Handles an expired task by removing it and calling appropriate error handling.
|
|
544
|
+
* @param {Object} item - The expired task item
|
|
545
|
+
* @returns {void}
|
|
546
|
+
* @private
|
|
547
|
+
*/
|
|
548
|
+
expireTask(item) {
|
|
549
|
+
if (item.status === "expired" || item.status === "canceled" || item.status === "completed") {
|
|
550
|
+
return; // Already handled
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
item.status = "expired";
|
|
554
|
+
this.tasks.delete(item.id);
|
|
555
|
+
this.running.delete(item);
|
|
556
|
+
|
|
557
|
+
const error = new Error(`Task expired after waiting ${this.now() - (item.readyAt || this.now())}ms in queue`);
|
|
558
|
+
error.type = "expire";
|
|
559
|
+
error.taskId = item.id;
|
|
560
|
+
|
|
561
|
+
if (item.callback) {
|
|
562
|
+
// Callback API - emit error event
|
|
563
|
+
try {
|
|
564
|
+
item.callback(error, null);
|
|
565
|
+
} catch (err) {
|
|
566
|
+
this.emit("error", { error: err, task: item });
|
|
567
|
+
}
|
|
568
|
+
// Emit error event for callback API
|
|
569
|
+
this.emit("error", { error, task: item });
|
|
570
|
+
} else if (item.reject) {
|
|
571
|
+
// Promise API - just reject, don't emit error event (handled by promise)
|
|
572
|
+
item.reject(error);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
439
576
|
/**
|
|
440
577
|
* Starts execution of a ready task.
|
|
441
578
|
* @param {Object} item - The task item to execute
|
|
@@ -559,8 +696,12 @@ export class HoldMyTask extends EventEmitter {
|
|
|
559
696
|
if (this.running.size === 0 && this.pendingHeap.size() === 0 && this.readyHeap.size() === 0) {
|
|
560
697
|
this.emit("drain");
|
|
561
698
|
} else if (this.isActive) {
|
|
562
|
-
// More tasks to run,
|
|
563
|
-
this.
|
|
699
|
+
// More tasks to run, reschedule immediately
|
|
700
|
+
if (this.options.smartScheduling) {
|
|
701
|
+
this.scheduleSmartTimeout();
|
|
702
|
+
} else {
|
|
703
|
+
this.schedulerTick();
|
|
704
|
+
}
|
|
564
705
|
}
|
|
565
706
|
});
|
|
566
707
|
}
|
|
@@ -581,4 +722,139 @@ export class HoldMyTask extends EventEmitter {
|
|
|
581
722
|
this.timeoutId = undefined;
|
|
582
723
|
}
|
|
583
724
|
}
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Calculates when the next scheduler run should happen and sets appropriate timeout.
|
|
728
|
+
* @private
|
|
729
|
+
* @returns {void}
|
|
730
|
+
*
|
|
731
|
+
* @description
|
|
732
|
+
* Smart scheduling that calculates the optimal time for the next scheduler run based on:
|
|
733
|
+
* - When the next pending task becomes ready
|
|
734
|
+
* - When delay periods end
|
|
735
|
+
* - Whether there are tasks that can run immediately
|
|
736
|
+
*
|
|
737
|
+
* Uses setTimeout for precise timing instead of constant polling intervals.
|
|
738
|
+
*/
|
|
739
|
+
scheduleSmartTimeout() {
|
|
740
|
+
if (!this.isActive || this.destroyed) return;
|
|
741
|
+
|
|
742
|
+
this.clearSchedulerTimers();
|
|
743
|
+
|
|
744
|
+
const now = this.now();
|
|
745
|
+
let nextRunTime = Infinity;
|
|
746
|
+
let shouldRunNow = false;
|
|
747
|
+
|
|
748
|
+
// Check if we have ready tasks that can run immediately
|
|
749
|
+
if (this.readyHeap.size() > 0 && this.running.size < this.options.concurrency) {
|
|
750
|
+
const delay = this.lastCompletedPriority !== null ? this.options.delays[this.lastCompletedPriority] || 0 : 0;
|
|
751
|
+
const delayActive = delay > 0 && now < this.nextAvailableTime;
|
|
752
|
+
|
|
753
|
+
if (!delayActive) {
|
|
754
|
+
shouldRunNow = true;
|
|
755
|
+
} else {
|
|
756
|
+
// Check for bypass tasks
|
|
757
|
+
const heapArray = this.readyHeap.heap.slice();
|
|
758
|
+
for (const task of heapArray) {
|
|
759
|
+
if (task.bypassDelay && (!task.expireAt || now < task.expireAt)) {
|
|
760
|
+
shouldRunNow = true;
|
|
761
|
+
break;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
if (!shouldRunNow) {
|
|
766
|
+
nextRunTime = Math.min(nextRunTime, this.nextAvailableTime);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
// Check when next pending task becomes ready
|
|
772
|
+
const nextPending = this.pendingHeap.peek();
|
|
773
|
+
if (nextPending) {
|
|
774
|
+
nextRunTime = Math.min(nextRunTime, nextPending.readyAt);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
// If we should run now or very soon, do it immediately
|
|
778
|
+
if (shouldRunNow || nextRunTime <= now + 1) {
|
|
779
|
+
// Use setImmediate to allow abort signals to be processed
|
|
780
|
+
setImmediate(() => this.runScheduler());
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// If we have a future time to schedule for
|
|
785
|
+
if (nextRunTime < Infinity) {
|
|
786
|
+
const delay = Math.min(nextRunTime - now, 2147483647); // Max 32-bit int for setTimeout
|
|
787
|
+
this.schedulerTimeout = setTimeout(() => {
|
|
788
|
+
this.runScheduler();
|
|
789
|
+
}, delay);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/**
|
|
794
|
+
* Runs the main scheduler logic and reschedules if needed.
|
|
795
|
+
* @private
|
|
796
|
+
* @returns {void}
|
|
797
|
+
*
|
|
798
|
+
* @description
|
|
799
|
+
* Executes the scheduler tick logic and then determines if more scheduling is needed.
|
|
800
|
+
* Tracks when scheduler last ran for healing mechanism.
|
|
801
|
+
*/
|
|
802
|
+
runScheduler() {
|
|
803
|
+
if (!this.isActive || this.destroyed) return;
|
|
804
|
+
|
|
805
|
+
this.lastSchedulerRun = this.now();
|
|
806
|
+
this.schedulerTick();
|
|
807
|
+
|
|
808
|
+
// Schedule next run if there's still work to do
|
|
809
|
+
this.scheduleSmartTimeout();
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/**
|
|
813
|
+
* Starts the self-healing interval that ensures scheduler continues working.
|
|
814
|
+
* @private
|
|
815
|
+
* @returns {void}
|
|
816
|
+
*
|
|
817
|
+
* @description
|
|
818
|
+
* Healing mechanism that periodically checks if the scheduler should be running
|
|
819
|
+
* but isn't due to timeout failures or other issues. Runs every healingInterval milliseconds.
|
|
820
|
+
*/
|
|
821
|
+
startHealingInterval() {
|
|
822
|
+
if (this.healingInterval) {
|
|
823
|
+
clearInterval(this.healingInterval);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
this.healingInterval = setInterval(() => {
|
|
827
|
+
if (!this.isActive || this.destroyed) return;
|
|
828
|
+
|
|
829
|
+
const now = this.now();
|
|
830
|
+
const hasWork = this.pendingHeap.size() > 0 || this.readyHeap.size() > 0;
|
|
831
|
+
const timeSinceLastRun = now - this.lastSchedulerRun;
|
|
832
|
+
const shouldHaveRun = hasWork && timeSinceLastRun > this.options.healingInterval;
|
|
833
|
+
|
|
834
|
+
// If we should have run but haven't, and we don't have an active timeout, heal
|
|
835
|
+
if (shouldHaveRun && !this.schedulerTimeout) {
|
|
836
|
+
console.warn(`HoldMyTask: Healing scheduler - ${timeSinceLastRun}ms since last run`);
|
|
837
|
+
this.runScheduler();
|
|
838
|
+
}
|
|
839
|
+
}, this.options.healingInterval);
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/**
|
|
843
|
+
* Clears all scheduler-related timers.
|
|
844
|
+
* @private
|
|
845
|
+
* @returns {void}
|
|
846
|
+
*
|
|
847
|
+
* @description
|
|
848
|
+
* Cleans up both the main scheduler timeout and the healing interval timer.
|
|
849
|
+
*/
|
|
850
|
+
clearSchedulerTimers() {
|
|
851
|
+
if (this.schedulerTimeout) {
|
|
852
|
+
clearTimeout(this.schedulerTimeout);
|
|
853
|
+
this.schedulerTimeout = null;
|
|
854
|
+
}
|
|
855
|
+
if (this.healingInterval) {
|
|
856
|
+
clearInterval(this.healingInterval);
|
|
857
|
+
this.healingInterval = null;
|
|
858
|
+
}
|
|
859
|
+
}
|
|
584
860
|
}
|