Auto-Commit: 2026-08-27 07:26:16

This commit is contained in:
Jannik committed 2026-08-27 07:26:16 +02:00
1 parent ed5cc23a35
commit 0a3b333f84
1753 files changed
+318589

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
## ISC License
Copyright (c) 2016, Lucas Merencia \<lucas.merencia@gmail.com\>
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+198
View File
@@ -0,0 +1,198 @@
# Node Cron
[![npm version](https://img.shields.io/npm/v/node-cron.svg?color=2f9d5f)](https://www.npmjs.com/package/node-cron)
[![npm downloads](https://img.shields.io/npm/dm/node-cron.svg?color=2f9d5f)](https://www.npmjs.com/package/node-cron)
[![used by](https://img.shields.io/badge/used%20by-220k%2B%20repos-2f9d5f)](https://github.com/node-cron/node-cron/network/dependents)
[![coverage](https://coveralls.io/repos/github/node-cron/node-cron/badge.svg?branch=main)](https://coveralls.io/github/node-cron/node-cron?branch=main)
[![zero dependencies](https://img.shields.io/badge/dependencies-0-2f9d5f)](https://www.npmjs.com/package/node-cron?activeTab=dependencies)
[![license](https://img.shields.io/npm/l/node-cron.svg?color=2f9d5f)](https://github.com/node-cron/node-cron/blob/main/LICENSE.md)
[![sponsor](https://img.shields.io/badge/%E2%9D%A4%20sponsor-2f9d5f)](https://github.com/sponsors/node-cron)
Job scheduling for Node.js with overlap prevention, distributed coordination, and background tasks. Schedule recurring tasks with cron expressions, prevent overlapping runs, coordinate across multiple instances, and run heavy jobs in isolated background processes. Zero dependencies, written in TypeScript.
### Full documentation: [nodecron.com](https://nodecron.com)
## Getting Started
```console
npm install node-cron
```
```javascript
import cron from 'node-cron';
cron.schedule('* * * * *', () => {
console.log('running a task every minute');
});
```
## Overlap Prevention
Long-running tasks can overlap when the next tick fires before the previous run finishes. `noOverlap` skips a run instead of stacking them:
```javascript
cron.schedule('* * * * *', async () => {
await slowJob();
}, { noOverlap: true });
```
## Distributed Coordination
Running multiple instances of your app? `distributed: true` ensures only one instance executes each scheduled fire. Out of the box it uses an env-var flag; for high availability, plug in a [Redis coordinator](https://nodecron.com/distributed-coordination):
```javascript
cron.schedule('0 3 * * *', runNightlyBackup, {
name: 'nightly-backup',
distributed: true,
});
```
## Background Tasks
Pass a file path instead of a function to run a job in an isolated forked process, so heavy work never blocks your event loop:
```javascript
cron.schedule('0 3 * * *', './tasks/backup.js');
```
> **Bundlers:** background tasks fork a helper that node-cron resolves relative to its own files in `node_modules`. If you bundle your app (esbuild, webpack, Rollup, etc.), mark node-cron as external so it stays on disk (`--external:node-cron`, or `externals: ['node-cron']` in webpack). Otherwise the fork fails with `Cannot find module '.../daemon.js'`. Inline function tasks are unaffected.
## Runtime Control
Every task exposes a single consistent interface for control and inspection:
```javascript
const task = cron.schedule('0 3 * * *', doWork, {
name: 'nightly-backup',
timezone: 'America/Sao_Paulo',
});
task.stop(); // pause
task.start(); // resume
task.destroy(); // remove permanently
task.getStatus(); // 'stopped' | 'idle' | 'running' | 'destroyed'
task.getNextRun(); // next scheduled Date, or null
task.lastRun(); // { date, result } or { date, error }, or null
```
## Events
Tasks emit lifecycle events for observability:
```javascript
task.on('execution:finished', (ctx) => console.log('result:', ctx.execution?.result));
task.on('execution:failed', (ctx) => console.error('failed:', ctx.execution?.error));
task.on('execution:overlap', () => console.warn('skipped: previous run still active'));
task.on('execution:skipped', (ctx) => console.log('not elected:', ctx.reason));
task.on('task:failed', () => task.start()); // background task's daemon died unexpectedly (crash, OOM-kill); restart manually
```
All events: `task:started`, `task:stopped`, `task:destroyed`, `task:failed`, `execution:started`, `execution:finished`, `execution:failed`, `execution:missed`, `execution:overlap`, `execution:maxReached`, `execution:skipped`. See [Events & Observability](https://nodecron.com/event-listening).
## Cron Syntax
```
# ┌────────────── second (optional)
# │ ┌──────────── minute
# │ │ ┌────────── hour
# │ │ │ ┌──────── day of month
# │ │ │ │ ┌────── month
# │ │ │ │ │ ┌──── day of week
# │ │ │ │ │ │
# * * * * * *
```
| field | value |
| ------------ | --------------------------------- |
| second | 0-59 (optional) |
| minute | 0-59 |
| hour | 0-23 |
| day of month | 1-31 (or `L` for the last day; `L-3` offset from last; `15W`, `LW` for nearest weekday) |
| month | 1-12 (or names) |
| day of week | 0-7 (or names, 0 or 7 are Sunday; `2#3`, `5L`) |
Supports ranges (`1-5`), steps (`*/2`), lists (`1,15`), named months/weekdays, `L` (last day of month), `L-n` (offset from the last day), `#` (nth weekday), `<weekday>L` (last weekday of month), `W` (nearest weekday), and `?` (alias for `*` in the day fields, for Quartz-style expressions). See the [Cron Syntax guide](https://nodecron.com/cron-syntax).
An inverted range wraps around the field instead of being rejected: `22-2` in the hour field means 22:00 through 02:59 (22,23,0,1,2), and `sat-sun` in the day-of-week field means saturday,sunday.
The `W` modifier in the day-of-month field fires on the nearest weekday (Monday-Friday) to a given day, without crossing the month boundary: `15W` is the nearest weekday to the 15th, `1W` the first weekday of the month, and `LW` the last weekday of the month. Only weekends are adjusted for; **there is no holiday awareness**.
The `L-n` form fires `n` days before the last day of the month (`L-3` is the third-to-last day). In months where the offset reaches before the 1st (e.g. `L-29` in February), it simply does not fire that month.
> **Note on Quartz:** `L`, `L-n`, `W`, `LW`, `#`, `<weekday>L` and `?` are borrowed from [Quartz](https://www.quartz-scheduler.org/), but node-cron is **not** Quartz-compatible. Two differences matter:
> - **Day-of-week numbering** is standard cron, not Quartz: `0-7` with `0`/`7` = Sunday and `1` = Monday. In Quartz `1` = Sunday, so the same numeric weekday fires on a different day.
> - **day-of-month and day-of-week** are combined with **AND** (both must match), and may both be set; Quartz instead treats them as mutually exclusive and requires `?` in one of them.
>
> `?` is accepted purely as an alias for `*` in the day fields so Quartz-style expressions parse, not as a semantic compatibility guarantee.
## When to Use node-cron
- Recurring jobs on a schedule (cron expressions with second-level precision)
- Overlap prevention for long-running tasks
- Coordinating scheduled tasks across multiple instances or replicas
- Running heavy jobs in isolated background processes
- Runtime control: start, stop, inspect, and observe tasks programmatically
## When to Consider Something Else
- **Durable job queues with retries and priorities**: use [BullMQ](https://bullmq.io), [Agenda](https://github.com/agenda/agenda), or [Sidequest](https://sidequestjs.com)
- **Persistent workflow orchestration**: use [Temporal](https://temporal.io) or [Inngest](https://inngest.com)
- **Exactly-once guarantees across crashes**: node-cron coordinates but does not persist state to a database; a queue or workflow engine is a better fit
## Options
```javascript
cron.schedule('0 3 * * *', task, {
name: 'nightly-backup',
timezone: 'America/Sao_Paulo',
noOverlap: true,
distributed: true,
maxExecutions: 10,
maxRandomDelay: 30000,
});
```
See [Scheduling Options](https://nodecron.com/scheduling-options) for the full list.
## Timezones and DST
Schedules match wall-clock time in the task's `timezone`. Across a daylight-saving fall-back the repeated hour runs once, so a sub-hourly schedule (for example `*/15`) can pause for up to the length of the DST shift during that hour. If you need a fixed interval to keep firing uninterrupted across DST transitions, use a zone without DST, for example `timezone: 'UTC'`. See [Timezones & DST](https://nodecron.com/timezones-and-dst) for the full model.
## Migrating from v3
v4 is a TypeScript rewrite with a smarter scheduler and a streamlined API. See the [Migration Guide](https://nodecron.com/migrating-from-v3).
## Sponsors
node-cron is zero-dependency infrastructure used in production by 220,000+ repositories. If it is part of your stack, sponsoring helps keep it tested, DST-correct, and maintained.
<!-- sponsors:begin -->
<!-- auto-generated from sponsors.tpl.md by @goreleaser/sponsors, do not edit by hand -->
<div align="center">
<p><strong>Silver sponsors</strong><br/> <a href="https://easysaas.at" target="_blank" rel="noopener sponsored"><img src="https://avatars.githubusercontent.com/u/24415042?s=64&v=4" alt="easySAAS" height="52"/></a>
</p>
</div>
<!-- sponsors:end -->
Become a sponsor on [**GitHub Sponsors**](https://github.com/sponsors/node-cron) or [**Open Collective**](https://opencollective.com/node-cron).
## Issues
Feel free to submit issues and enhancement requests [here](https://github.com/node-cron/node-cron/issues).
## Contributing
In general, we follow the "fork-and-pull" Git workflow.
- Fork the repo on GitHub;
- Commit changes to a branch in your fork;
- Pull request "upstream" with your changes;
NOTE: Be sure to merge the latest from "upstream" before making a pull request!
Please do not contribute code you did not write yourself, unless you are certain you have the legal ability to do so. Also ensure all contributed code can be distributed under the ISC License.
## License
node-cron is under [ISC License](https://github.com/node-cron/node-cron/blob/main/LICENSE.md).
+1261
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_shared.cjs","sources":["../src/create-id.ts","../src/logger.ts","../src/promise/tracked-promise.ts","../src/scheduler/plan-beat.ts","../src/scheduler/runner.ts","../src/pattern/conversion/month-names-conversion.ts","../src/pattern/conversion/week-day-names-conversion.ts","../src/pattern/conversion/asterisk-to-range-conversion.ts","../src/pattern/conversion/range-conversion.ts","../src/pattern/conversion/nicknames.ts","../src/pattern/conversion/index.ts","../src/time/localized-time.ts","../src/time/day-of-month.ts","../src/time/day-of-week.ts","../src/time/matcher-walker.ts","../src/time/time-matcher.ts","../src/tasks/state-machine.ts","../src/coordinator/env-var-run-coordinator.ts","../src/coordinator/run-coordinator.ts","../src/tasks/inline-scheduled-task.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["randomUUID","EventEmitter"],"mappings":";;;;;SAEgB,QAAQ,GAAA;IACtB,OAAOA,sBAAU,EAAE;AACrB;;ACUA,MAAM,WAAW,GAA6B;AAC5C,IAAA,IAAI,EAAE,UAAU;AAChB,IAAA,IAAI,EAAE,UAAU;AAChB,IAAA,KAAK,EAAE,U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S,EACT,WAAmB,EACnB,YAAkC,EAAA;IAElC,MAAM,MAAM,GAAW,EAAE;IACzB,IAAI,IAAI,GAAG,QAAQ;IAEnB,OAAO,IAAI,EAAE;AACX,QAAA,MAAM,KAAK,GAAG,GAAG,CAAC,OAAO,EAAE;AAC3B,QAAA,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,EAAE;AAI7B,QAAA,IAAI,KAAK,GAAG,MAAM,EAAE;AAClB,YAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE;QAC/B;AAEA,QAAA,MAAM,IAAI,GAAG,YAAY,CAAC,IAAI,CAAC;AAK/B,QAAA,IAAI,IAAI,CAAC,OAAO,EAAE,IAAI,MAAM,EAAE;YAC5B,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,CAAC,GAAG,CAAC,EAAE;QAC5C;QAEA,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,EAAE,GAAG,MAAM;AACnC,QAAA,MAAM,MAAM,GAAG,KAAK,GAAG,MAAM;QAK7B,IAAI,MAAM,IAAI,WAAW,IAAI,MAAM,GAAG,GAAG,EAAE;YACzC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE;QACpC;AAGA,QAAA,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC;QACjB,IAAI,GAAG,IAAI;IACb;AACF;;ACnDA,MAAM,kLine truncated
+1247
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"_shared.js","sources":["../src/create-id.ts","../src/logger.ts","../src/promise/tracked-promise.ts","../src/scheduler/plan-beat.ts","../src/scheduler/runner.ts","../src/pattern/conversion/month-names-conversion.ts","../src/pattern/conversion/week-day-names-conversion.ts","../src/pattern/conversion/asterisk-to-range-conversion.ts","../src/pattern/conversion/range-conversion.ts","../src/pattern/conversion/nicknames.ts","../src/pattern/conversion/index.ts","../src/time/localized-time.ts","../src/time/day-of-month.ts","../src/time/day-of-week.ts","../src/time/matcher-walker.ts","../src/time/time-matcher.ts","../src/tasks/state-machine.ts","../src/coordinator/env-var-run-coordinator.ts","../src/coordinator/run-coordinator.ts","../src/tasks/inline-scheduled-task.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":[],"mappings":";;;SAEgB,QAAQ,GAAA;IACtB,OAAO,UAAU,EAAE;AACrB;;ACUA,MAAM,WAAW,GAA6B;AAC5C,IAAA,IAAI,EAAE,UAAU;AAChB,IAAA,IAAI,EAAE,UAAU;AAChB,IAAA,KAAK,EAAE,UAAU;AACjB,IAAA,KAAK,EAAE,UAAU;CAClB;AAED,MAAM,KAAK,GAAG,UAAU;AACxB,MAAM,KAAK,GAAG,SAAS;AAEvB,SAAS,GAAG,CAAC,KAAe,EAAE,OAAe,EAAE,KAAW,EAAA;IACxD,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;AAC1C,IAAA,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,CAAC;AAChC,IAAA,MAAM,MAAM,GAAG,CAAA,CAAA,EAAI,SAAS,CAAA,QAAA,EAAW,OAAO,CAAC,GAAG,CAAA,EAAA,EAAK,KAAK,CAAA,WAAA,EAAc,KAAK,IAAI,KAAK,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA,EAAI,KAAK,EAAE;AAC5G,IAAA,MAAM,MAAM,GAAG,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,OAAO,EAAE;IAErC,QAAQ,KAAK;AACX,QAAA,KAAK,OAAO;YACV,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC;YAClC;AACF,QAAA,KAAK,OAAO;YACR,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC;YAClC;AACJ,QAAA,KAAK,MAAM;AACT,YAAA,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC;YACpB;AACF,QAAA,K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F;;ACnDA,MAAM,kCAAkC,GAAG,IAAI;AAU/C,SAAS,SAAS,Line truncated
+180
View File
@@ -0,0 +1,180 @@
'use strict';
var url = require('url');
var inlineScheduledTask = require('./_shared.cjs');
require('events');
require('node:crypto');
const DEFAULT_REPLY_TIMEOUT_MS = 5000;
class IpcRunCoordinator {
channel;
replyTimeoutMs;
pending = new Map();
constructor(channel, replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS) {
this.channel = channel;
this.replyTimeoutMs = replyTimeoutMs;
this.channel.on('message', (message) => {
if (message?.type !== 'coordinator:result')
return;
const resolve = this.pending.get(message.reqId);
if (resolve) {
this.pending.delete(message.reqId);
resolve(message);
}
});
}
shouldRun(key, ttlMs) {
const reqId = inlineScheduledTask.createID();
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
this.pending.delete(reqId);
reject(new Error(`Run coordinator reply timed out after ${this.replyTimeoutMs}ms`));
}, this.replyTimeoutMs);
this.pending.set(reqId, (result) => {
clearTimeout(timeoutId);
if (result.error)
reject(new Error(result.error));
else
resolve(result.allowed);
});
this.channel.send?.({ type: 'coordinator:shouldRun', key, ttlMs, reqId });
});
}
onComplete(key) {
this.channel.send?.({ type: 'coordinator:complete', key });
return Promise.resolve();
}
}
async function startDaemon(message) {
const script = await importTaskModule(message.path);
const options = { ...(message.options || {}), logger: inlineScheduledTask.noopLogger };
if (options.distributed) {
options.runCoordinator = new IpcRunCoordinator(process);
}
const task = new inlineScheduledTask.InlineScheduledTask(message.cron, script.task, options);
task.on('task:started', (context => sendEvent('task:started', context)));
task.on('task:stopped', (context => sendEvent('task:stopped', context)));
task.on('task:destroyed', (context => sendEvent('task:destroyed', context)));
task.on('execution:started', (context => sendEvent('execution:started', context)));
task.on('execution:finished', (context => sendEvent('execution:finished', context)));
task.on('execution:failed', (context => sendEvent('execution:failed', context)));
task.on('execution:missed', (context => sendEvent('execution:missed', context)));
task.on('execution:overlap', (context => sendEvent('execution:overlap', context)));
task.on('execution:maxReached', (context => sendEvent('execution:maxReached', context)));
task.on('execution:skipped', (context => sendEvent('execution:skipped', context)));
if (process.send)
process.send({ event: 'daemon:started' });
task.start();
return task;
}
async function importTaskModule(path) {
try {
return await import(path);
}
catch (firstError) {
try {
return await import(url.fileURLToPath(path));
}
catch {
throw firstError;
}
}
}
function sendEvent(event, context) {
const message = { event: event, context: safelySerializeContext(context) };
if (context.execution?.error) {
message.jsonError = serializeError(context.execution?.error);
}
if (process.send)
process.send(message);
}
function serializeError(err) {
const plain = {
name: err.name,
message: err.message,
stack: err.stack,
...Object.getOwnPropertyNames(err)
.filter(k => !['name', 'message', 'stack'].includes(k))
.reduce((acc, k) => {
acc[k] = err[k];
return acc;
}, {})
};
return JSON.stringify(plain);
}
function safelySerializeContext(context) {
const safeContext = {
date: context.date,
dateLocalIso: context.dateLocalIso,
triggeredAt: context.triggeredAt
};
if (context.reason) {
safeContext.reason = context.reason;
}
if (context.task) {
safeContext.task = {
id: context.task.id,
name: context.task.name,
state: context.task.getStatus()
};
}
if (context.execution) {
safeContext.execution = {
id: context.execution.id,
reason: context.execution.reason,
startedAt: context.execution.startedAt,
finishedAt: context.execution.finishedAt,
hasError: !!context.execution.error,
result: context.execution.result
};
}
return safeContext;
}
function bind() {
let task;
process.on('message', async (message) => {
switch (message.command) {
case 'task:start':
try {
task = await startDaemon(message);
}
catch (error) {
if (process.send)
process.send({ event: 'daemon:error', jsonError: serializeError(error) });
}
return task;
case 'task:stop':
if (task)
task.stop();
return task;
case 'task:destroy':
if (task)
task.destroy();
return task;
case 'task:execute':
if (!task) {
sendEvent('execution:failed', {
date: new Date(),
dateLocalIso: new Date().toISOString(),
triggeredAt: new Date(),
execution: { id: message.executionId ?? inlineScheduledTask.createID(), reason: 'invoked', error: new Error('Cannot execute: no task loaded') }
});
return task;
}
try {
await task.execute(message.executionId);
}
catch (error) {
inlineScheduledTask.logger.debug('Daemon task:execute failed:', error);
}
return task;
}
});
process.on('disconnect', () => process.exit(0));
}
bind();
exports.bind = bind;
exports.startDaemon = startDaemon;
//# sourceMappingURL=daemon.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"daemon.cjs","sources":["../src/coordinator/ipc-run-coordinator.ts","../src/tasks/background-scheduled-task/daemon.ts"],"sourcesContent":[null,null],"names":["createID","noopLogger","InlineScheduledTask","fileURLToPath","logger"],"mappings":";;;;;;;AAiBA,MAAM,wBAAwB,GAAG,IAAI;MAUxB,iBAAiB,CAAA;AAGR,IAAA,OAAA;AAA6B,IAAA,cAAA;AAFzC,IAAA,OAAO,GAAG,IAAI,GAAG,EAA+C;IAExE,WAAA,CAAoB,OAAmB,EAAU,cAAA,GAAyB,wBAAwB,EAAA;QAA9E,IAAA,CAAA,OAAO,GAAP,OAAO;QAAsB,IAAA,CAAA,cAAc,GAAd,cAAc;QAC7D,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAY,KAAI;AAC1C,YAAA,IAAI,OAAO,EAAE,IAAI,KAAK,oBAAoB;gBAAE;AAC5C,YAAA,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC;YAC/C,IAAI,OAAO,EAAE;gBACX,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC;gBAClC,OAAO,CAAC,OAAO,CAAC;YAClB;AACF,QAAA,CAAC,CAAC;IACJ;IAEA,SAAS,CAAC,GAAW,EAAE,KAAa,EAAA;AAClC,QAAA,MAAM,KAAK,GAAGA,4BAAQ,EAAE;QACxB,OAAO,IAAI,OAAO,CAAU,CAAC,OAAO,EAAE,MAAM,KAAI;AAC9C,YAAA,MAAM,SAAS,GAAG,UAAU,CAAC,MAAK;AAChC,gBAAA,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC;gBAC1B,MAAM,CAAC,IAAI,KAAK,CAAC,CAAA,sCAAA,EAAyC,IAAI,CAAC,cAAc,CAAA,EAAA,CAAI,C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E,OAAO,CAAC,YAAY;QAClC,WAAW,EAAE,OAAO,CAAC;KACtB;AAED,IAAA,IAAI,OAAO,CAAC,MAAM,EAAE;AAClB,QAAA,WAAW,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM;IACrC;AAGA,IAAA,IAAI,OAAO,CAAC,IAAI,EAAE;QAChB,WAAW,CAAC,IAAI,GAAG;AACjB,YAAA,EAAE,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE;AACnB,YAAA,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,IAAI;AACvB,YAAA,KAAK,EAAE,OAAO,CAAC,IAAI,CAAC,SAAS;SAC9B;IACH;AAEA,IAAA,IAAI,OAAO,CAAC,SAAS,EAAE;QACrB,WAAW,CAAC,SAAS,GAAG;AACtB,YAAA,EAAE,EAAE,OAAO,CAAC,SAAS,CAAC,EAAE;AACxB,YAAA,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC,MAAM;AAChC,YAAA,SAAS,EAAE,OAAO,CAAC,SAAS,CAAC,SAAS;AACtC,YAAA,UAAU,EAAE,OAAO,CAAC,SAAS,CAAC,UAAU;AACxC,YAAA,QAAQ,EAAE,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,KAAK;AACnC,YAAA,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC;SAC3B;IACH;AAEA,IAAA,OAAO,WAAW;AACpB;SAGgB,IAAI,GAAA;AAClB,IAAA,IAAI,IAAyB;IAE7B,OAAO,CAAC,EAALine truncated
+177
View File
@@ -0,0 +1,177 @@
import { fileURLToPath } from 'url';
import { a as createID, I as InlineScheduledTask, n as noopLogger, l as logger } from './_shared.js';
import 'events';
import 'node:crypto';
const DEFAULT_REPLY_TIMEOUT_MS = 5000;
class IpcRunCoordinator {
channel;
replyTimeoutMs;
pending = new Map();
constructor(channel, replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS) {
this.channel = channel;
this.replyTimeoutMs = replyTimeoutMs;
this.channel.on('message', (message) => {
if (message?.type !== 'coordinator:result')
return;
const resolve = this.pending.get(message.reqId);
if (resolve) {
this.pending.delete(message.reqId);
resolve(message);
}
});
}
shouldRun(key, ttlMs) {
const reqId = createID();
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
this.pending.delete(reqId);
reject(new Error(`Run coordinator reply timed out after ${this.replyTimeoutMs}ms`));
}, this.replyTimeoutMs);
this.pending.set(reqId, (result) => {
clearTimeout(timeoutId);
if (result.error)
reject(new Error(result.error));
else
resolve(result.allowed);
});
this.channel.send?.({ type: 'coordinator:shouldRun', key, ttlMs, reqId });
});
}
onComplete(key) {
this.channel.send?.({ type: 'coordinator:complete', key });
return Promise.resolve();
}
}
async function startDaemon(message) {
const script = await importTaskModule(message.path);
const options = { ...(message.options || {}), logger: noopLogger };
if (options.distributed) {
options.runCoordinator = new IpcRunCoordinator(process);
}
const task = new InlineScheduledTask(message.cron, script.task, options);
task.on('task:started', (context => sendEvent('task:started', context)));
task.on('task:stopped', (context => sendEvent('task:stopped', context)));
task.on('task:destroyed', (context => sendEvent('task:destroyed', context)));
task.on('execution:started', (context => sendEvent('execution:started', context)));
task.on('execution:finished', (context => sendEvent('execution:finished', context)));
task.on('execution:failed', (context => sendEvent('execution:failed', context)));
task.on('execution:missed', (context => sendEvent('execution:missed', context)));
task.on('execution:overlap', (context => sendEvent('execution:overlap', context)));
task.on('execution:maxReached', (context => sendEvent('execution:maxReached', context)));
task.on('execution:skipped', (context => sendEvent('execution:skipped', context)));
if (process.send)
process.send({ event: 'daemon:started' });
task.start();
return task;
}
async function importTaskModule(path) {
try {
return await import(path);
}
catch (firstError) {
try {
return await import(fileURLToPath(path));
}
catch {
throw firstError;
}
}
}
function sendEvent(event, context) {
const message = { event: event, context: safelySerializeContext(context) };
if (context.execution?.error) {
message.jsonError = serializeError(context.execution?.error);
}
if (process.send)
process.send(message);
}
function serializeError(err) {
const plain = {
name: err.name,
message: err.message,
stack: err.stack,
...Object.getOwnPropertyNames(err)
.filter(k => !['name', 'message', 'stack'].includes(k))
.reduce((acc, k) => {
acc[k] = err[k];
return acc;
}, {})
};
return JSON.stringify(plain);
}
function safelySerializeContext(context) {
const safeContext = {
date: context.date,
dateLocalIso: context.dateLocalIso,
triggeredAt: context.triggeredAt
};
if (context.reason) {
safeContext.reason = context.reason;
}
if (context.task) {
safeContext.task = {
id: context.task.id,
name: context.task.name,
state: context.task.getStatus()
};
}
if (context.execution) {
safeContext.execution = {
id: context.execution.id,
reason: context.execution.reason,
startedAt: context.execution.startedAt,
finishedAt: context.execution.finishedAt,
hasError: !!context.execution.error,
result: context.execution.result
};
}
return safeContext;
}
function bind() {
let task;
process.on('message', async (message) => {
switch (message.command) {
case 'task:start':
try {
task = await startDaemon(message);
}
catch (error) {
if (process.send)
process.send({ event: 'daemon:error', jsonError: serializeError(error) });
}
return task;
case 'task:stop':
if (task)
task.stop();
return task;
case 'task:destroy':
if (task)
task.destroy();
return task;
case 'task:execute':
if (!task) {
sendEvent('execution:failed', {
date: new Date(),
dateLocalIso: new Date().toISOString(),
triggeredAt: new Date(),
execution: { id: message.executionId ?? createID(), reason: 'invoked', error: new Error('Cannot execute: no task loaded') }
});
return task;
}
try {
await task.execute(message.executionId);
}
catch (error) {
logger.debug('Daemon task:execute failed:', error);
}
return task;
}
});
process.on('disconnect', () => process.exit(0));
}
bind();
export { bind, startDaemon };
//# sourceMappingURL=daemon.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"daemon.js","sources":["../src/coordinator/ipc-run-coordinator.ts","../src/tasks/background-scheduled-task/daemon.ts"],"sourcesContent":[null,null],"names":[],"mappings":";;;;;AAiBA,MAAM,wBAAwB,GAAG,IAAI;MAUxB,iBAAiB,CAAA;AAGR,IAAA,OAAA;AAA6B,IAAA,cAAA;AAFzC,IAAA,OAAO,GAAG,IAAI,GAAG,EAA+C;IAExE,WAAA,CAAoB,OAAmB,EAAU,cAAA,GAAyB,wBAAwB,EAAA;QAA9E,IAAA,CAAA,OAAO,GAAP,OAAO;QAAsB,IA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AACtB,YAAA,EAAE,EAAE,OAAO,CAAC,SAAS,CAAC,EAAE;AACxB,YAAA,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC,MAAM;AAChC,YAAA,SAAS,EAAE,OAAO,CAAC,SAAS,CAAC,SAAS;AACtC,YAAA,UAAU,EAAE,OAAO,CAAC,SAAS,CAAC,UAAU;AACxC,YAAA,QAAQ,EAAE,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,KAAK;AACnC,YAAA,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC;SAC3B;IACH;AAEA,IAAA,OAAO,WAAW;AACpB;SAGgB,IAAI,GAAA;AAClB,IAAA,IAAI,IAAyB;IAE7B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,OAAO,OAAY,KAAI;AAC3C,QAAA,QAAO,OAAO,CAAC,OAAO;AACtB,YAAA,KAAK,YLine truncated
+757
View File
@@ -0,0 +1,757 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var inlineScheduledTask = require('./_shared.cjs');
var path = require('path');
var url = require('url');
var child_process = require('child_process');
var events = require('events');
require('node:crypto');
const tasks = new Map();
class TaskRegistry {
add(task) {
if (this.has(task.id)) {
throw Error(`task ${task.id} already registered!`);
}
tasks.set(task.id, task);
task.on('task:destroyed', () => {
this.remove(task);
});
}
get(taskId) {
return tasks.get(taskId);
}
remove(task) {
if (this.has(task.id)) {
tasks.delete(task.id);
task.destroy();
}
}
all() {
return tasks;
}
has(taskId) {
return tasks.has(taskId);
}
killAll() {
tasks.forEach(id => this.remove(id));
}
}
const validationRegex = /^(?:\d+|\*|\*\/\d+)$/;
const ALLOWED_CHARS_REGEX = /^[a-zA-Z0-9-*/,#? ]+$/;
function splitFields(resolved) {
return resolved.replace(/\s{2,}/g, ' ').trim().split(' ');
}
function isValidExpression(expression, min, max) {
const options = expression;
for (const option of options) {
const optionAsInt = parseInt(option, 10);
if ((!Number.isNaN(optionAsInt) &&
(optionAsInt < min || optionAsInt > max)) ||
!validationRegex.test(option))
return false;
}
return true;
}
function isInvalidSecond(expression) {
return !isValidExpression(expression, 0, 59);
}
function isInvalidMinute(expression) {
return !isValidExpression(expression, 0, 59);
}
function isInvalidHour(expression) {
return !isValidExpression(expression, 0, 23);
}
const DAY_OF_MONTH_W_TOKEN = /^(\d{1,2}|L)W$/i;
const DAY_OF_MONTH_OFFSET_TOKEN = /^L-(\d{1,2})$/i;
function isInvalidDayOfMonth(expression) {
const days = expression.filter((value) => {
if (value === 'L')
return false;
const weekday = DAY_OF_MONTH_W_TOKEN.exec(String(value));
if (weekday) {
if (weekday[1] === 'L')
return false;
const target = parseInt(weekday[1], 10);
return target < 1 || target > 31;
}
const offset = DAY_OF_MONTH_OFFSET_TOKEN.exec(String(value));
if (offset) {
const n = parseInt(offset[1], 10);
return n < 1 || n > 30;
}
return true;
});
return !isValidExpression(days, 1, 31);
}
function hasInvalidWModifier(rawDayOfMonth) {
if (!/w/i.test(rawDayOfMonth))
return false;
return rawDayOfMonth.split(',').some((token) => {
const value = token.trim();
if (!/w/i.test(value))
return false;
return !DAY_OF_MONTH_W_TOKEN.test(value);
});
}
function isInvalidMonth(expression) {
return !isValidExpression(expression, 1, 12);
}
function isInvalidWeekDay(expression) {
const days = expression.filter((value) => !inlineScheduledTask.isNthWeekdayToken(value) && !/^[0-7]L$/.test(value));
return !isValidExpression(days, 0, 7);
}
const MAX_DAYS_IN_MONTH = {
1: 31, 2: 29, 3: 31, 4: 30, 5: 31, 6: 30,
7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31,
};
function isImpossibleDayOfMonth(days, months) {
if (days.some((day) => typeof day !== 'number'))
return false;
return !months.some((month) => days.some((day) => day <= MAX_DAYS_IN_MONTH[month]));
}
function validateFields(patterns, executablePatterns) {
if (isInvalidSecond(executablePatterns[0]))
throw new Error(`${patterns[0]} is a invalid expression for second`);
if (isInvalidMinute(executablePatterns[1]))
throw new Error(`${patterns[1]} is a invalid expression for minute`);
if (isInvalidHour(executablePatterns[2]))
throw new Error(`${patterns[2]} is a invalid expression for hour`);
if (isInvalidDayOfMonth(executablePatterns[3]) || hasInvalidWModifier(patterns[3]))
throw new Error(`${patterns[3]} is a invalid expression for day of month`);
if (isInvalidMonth(executablePatterns[4]))
throw new Error(`${patterns[4]} is a invalid expression for month`);
if (isInvalidWeekDay(executablePatterns[5]))
throw new Error(`${patterns[5]} is a invalid expression for week day`);
if (isImpossibleDayOfMonth(executablePatterns[3], executablePatterns[4]))
throw new Error(`${patterns[3]} ${patterns[4]} is an impossible day of month for the given month`);
}
const FIELDS = [
{ key: 'second', label: 'second', invalid: isInvalidSecond },
{ key: 'minute', label: 'minute', invalid: isInvalidMinute },
{ key: 'hour', label: 'hour', invalid: isInvalidHour },
{ key: 'dayOfMonth', label: 'day of month', invalid: isInvalidDayOfMonth },
{ key: 'month', label: 'month', invalid: isInvalidMonth },
{ key: 'dayOfWeek', label: 'week day', invalid: isInvalidWeekDay },
];
function validateDetailed$1(pattern) {
if (typeof pattern !== 'string')
return { valid: false, errors: [{ field: 'expression', message: 'pattern must be a string' }] };
const resolved = inlineScheduledTask.resolveNickname(pattern);
if (!ALLOWED_CHARS_REGEX.test(resolved))
return { valid: false, errors: [{ field: 'expression', value: pattern, message: 'pattern includes illegal characters' }] };
const raw = splitFields(resolved);
if (raw.length !== 5 && raw.length !== 6)
return { valid: false, errors: [{ field: 'expression', value: pattern, message: `expected 5 or 6 fields but got ${raw.length}` }] };
const patterns = raw.length === 5 ? ['0', ...raw] : raw;
const executable = inlineScheduledTask.convertExpression(pattern);
const errors = [];
FIELDS.forEach((f, i) => {
const rawWMisuse = f.key === 'dayOfMonth' && hasInvalidWModifier(patterns[i]);
if (f.invalid(executable[i]) || rawWMisuse)
errors.push({ field: f.key, value: patterns[i], message: `${patterns[i]} is a invalid expression for ${f.label}` });
});
if (!errors.length && isImpossibleDayOfMonth(executable[3], executable[4])) {
errors.push({
field: 'dayOfMonth',
value: patterns[3],
message: `${patterns[3]} ${patterns[4]} is an impossible day of month for the given month`,
});
}
if (errors.length)
return { valid: false, errors };
return {
valid: true,
errors: [],
fields: {
second: executable[0],
minute: executable[1],
hour: executable[2],
dayOfMonth: executable[3],
month: executable[4],
dayOfWeek: executable[5],
},
};
}
function parse$1(pattern) {
const result = validateDetailed$1(pattern);
if (!result.valid)
throw new Error(result.errors[0].message);
return result.fields;
}
function validate$1(pattern) {
if (typeof pattern !== 'string')
throw new TypeError('pattern must be a string!');
const resolved = inlineScheduledTask.resolveNickname(pattern);
if (!ALLOWED_CHARS_REGEX.test(resolved))
throw new TypeError('pattern includes illegal characters!');
const raw = splitFields(resolved);
if (raw.length !== 5 && raw.length !== 6)
throw new Error(`expected 5 or 6 fields but got ${raw.length}`);
const patterns = raw.length === 5 ? ['0', ...raw] : raw;
const executablePatterns = inlineScheduledTask.convertExpression(resolved);
validateFields(patterns, executablePatterns);
}
const daemonPath = path.resolve(path.dirname(__filename), 'daemon.cjs');
class TaskEmitter extends events.EventEmitter {
}
class BackgroundScheduledTask {
emitter;
id;
name;
cronExpression;
taskPath;
options;
forkProcess;
stateMachine;
logger;
suppressMissedWarning;
timeMatcher;
runCount;
runCoordinator;
_lastRun = null;
executing = false;
killPending = false;
pendingKillCleanup;
currentExecution;
killRequested = false;
startPromise;
constructor(cronExpression, taskPath, options) {
this.cronExpression = cronExpression;
this.taskPath = taskPath;
this.options = options;
this.id = inlineScheduledTask.createID();
this.name = options?.name || this.id;
this.emitter = new TaskEmitter();
this.stateMachine = new inlineScheduledTask.StateMachine('stopped');
this.timeMatcher = new inlineScheduledTask.TimeMatcher(cronExpression, options?.timezone);
this.runCount = 0;
this.on('execution:started', (context) => {
if (context?.execution?.reason === 'scheduled')
this.runCount++;
this.executing = true;
this.currentExecution = context?.execution;
});
this.on('execution:finished', (context) => { this.executing = false; this.currentExecution = undefined; this.recordLastRun(context.execution); });
this.on('execution:failed', (context) => { this.executing = false; this.currentExecution = undefined; this.recordLastRun(context.execution); });
this.logger = options?.logger || inlineScheduledTask.logger;
this.suppressMissedWarning = options?.suppressMissedWarning || false;
this.runCoordinator = options?.distributed ? inlineScheduledTask.resolveRunCoordinator(options?.runCoordinator) : undefined;
this.on('task:stopped', () => {
this.killForkWhenSettled();
if (this.stateMachine.state !== 'destroyed') {
this.stateMachine.changeState('stopped');
}
});
this.on('task:destroyed', () => {
this.killForkWhenSettled();
this.stateMachine.changeState('destroyed');
});
}
getNextRun() {
if (this.stateMachine.state !== 'stopped') {
return this.timeMatcher.getNextMatch(new Date());
}
return null;
}
getNextRuns(count) {
const runs = [];
let from = new Date();
for (let i = 0; i < count; i++) {
from = this.timeMatcher.getNextMatch(from);
runs.push(from);
}
return runs;
}
match(date) {
return this.timeMatcher.match(date);
}
msToNext() {
const next = this.getNextRun();
return next ? next.getTime() - Date.now() : null;
}
isBusy() {
return this.getStatus() === 'running';
}
runsLeft() {
if (this.options?.maxExecutions == null)
return undefined;
return Math.max(0, this.options.maxExecutions - this.runCount);
}
getPattern() {
return this.cronExpression;
}
lastRun() {
return this._lastRun;
}
recordLastRun(execution) {
if (!execution)
return;
const raw = execution.finishedAt ?? execution.startedAt;
const date = raw ? new Date(raw) : new Date();
const lastRun = { date };
if (execution.error) {
lastRun.error = execution.error;
}
else {
lastRun.result = execution.result;
}
this._lastRun = lastRun;
}
killForkWhenSettled() {
if (!this.forkProcess)
return;
if (!this.executing) {
this.killFork();
return;
}
if (this.killPending)
return;
this.killPending = true;
const onSettled = () => this.killFork();
this.once('execution:finished', onSettled);
this.once('execution:failed', onSettled);
this.pendingKillCleanup = () => {
this.off('execution:finished', onSettled);
this.off('execution:failed', onSettled);
};
}
clearPendingKillWait() {
this.pendingKillCleanup?.();
this.pendingKillCleanup = undefined;
this.killPending = false;
}
killFork() {
this.clearPendingKillWait();
this.killRequested = true;
this.forkProcess?.kill();
this.forkProcess = undefined;
}
handleUnexpectedExit(code, signal) {
this.clearPendingKillWait();
const erro = new Error(`daemon exited unexpectedly (code ${code}, signal ${signal})`);
this.logger.error(erro);
if (this.executing) {
const execution = { id: inlineScheduledTask.createID(), reason: 'scheduled', ...this.currentExecution, error: erro, finishedAt: new Date() };
this.emitter.emit('execution:failed', this.createContext(new Date(), execution));
}
try {
this.stateMachine.changeState('stopped');
}
catch (err) {
this.logger.error(err);
}
const context = this.createContext(new Date());
context.error = erro;
this.emitter.emit('task:failed', context);
this.forkProcess = undefined;
}
start() {
if (this.stateMachine.state === 'destroyed') {
return Promise.resolve();
}
if (this.startPromise) {
return this.startPromise;
}
if (this.forkProcess) {
return Promise.resolve();
}
this.startPromise = this.forkAndStart().finally(() => {
this.startPromise = undefined;
});
return this.startPromise;
}
forkAndStart() {
return new Promise((resolve, reject) => {
const startTimeout = this.options?.startTimeout ?? 5000;
const failStart = (error) => {
clearTimeout(timeout);
this.killFork();
reject(error);
};
const timeout = setTimeout(() => {
failStart(new Error(`Start operation timed out after ${startTimeout}ms. The background task file may have failed to load or taken too long to import; ` +
`verify it runs on its own and consider increasing the \`startTimeout\` option.`));
}, startTimeout);
this.killRequested = false;
let startSucceeded = false;
try {
this.forkProcess = child_process.fork(daemonPath);
this.forkProcess.on('error', (err) => {
failStart(new Error(`Error on daemon: ${err.message}`));
});
this.forkProcess.on('exit', (code, signal) => {
if (this.killRequested) {
this.killRequested = false;
return;
}
if (code !== 0 && signal !== 'SIGTERM') {
if (startSucceeded) {
this.handleUnexpectedExit(code, signal);
return;
}
const erro = new Error(`node-cron daemon exited with code ${code || signal}`);
this.logger.error(erro);
failStart(erro);
}
});
this.forkProcess.on('message', (message) => {
if (message.type === 'coordinator:shouldRun') {
void this.handleShouldRun(message);
return;
}
if (message.type === 'coordinator:complete') {
this.runCoordinator?.onComplete?.(message.key)?.catch?.((err) => this.logger.error('Run coordinator onComplete failed', err));
return;
}
if (message.event === 'daemon:error') {
failStart(message.jsonError ? deserializeError(message.jsonError) : new Error('Background task failed to start'));
return;
}
if (message.jsonError) {
if (message.context?.execution) {
message.context.execution.error = deserializeError(message.jsonError);
delete message.jsonError;
}
}
if (message.context?.task?.state) {
this.stateMachine.changeState(message.context?.task?.state);
}
if (message.context) {
const execution = message.context?.execution;
delete execution?.hasError;
const context = this.createContext(new Date(message.context.date), execution, message.context.reason);
this.logEvent(message.event, context);
this.emitter.emit(message.event, context);
}
});
this.once('task:started', () => {
startSucceeded = true;
this.stateMachine.changeState('idle');
clearTimeout(timeout);
resolve(undefined);
});
this.forkProcess.send({
command: 'task:start',
path: this.taskPath,
cron: this.cronExpression,
options: serializableOptions(this.options)
});
}
catch (error) {
failStart(error);
}
});
}
stop() {
return new Promise((resolve, reject) => {
if (this.stateMachine.state === 'destroyed') {
return resolve(undefined);
}
if (!this.forkProcess) {
this.emitter.emit('task:stopped');
return resolve(undefined);
}
const timeoutId = setTimeout(() => {
clearTimeout(timeoutId);
this.killFork();
reject(new Error('Stop operation timed out'));
}, 5000);
const cleanupAndResolve = () => {
clearTimeout(timeoutId);
this.off('task:stopped', onStopped);
resolve(undefined);
};
const onStopped = () => {
cleanupAndResolve();
};
this.once('task:stopped', onStopped);
this.forkProcess.send({
command: 'task:stop'
});
});
}
getStatus() {
return this.stateMachine.state;
}
unref() {
if (!this.forkProcess)
return;
this.forkProcess.unref();
this.forkProcess.channel?.unref();
}
ref() {
if (!this.forkProcess)
return;
this.forkProcess.ref();
this.forkProcess.channel?.ref();
}
destroy() {
return new Promise((resolve, reject) => {
if (this.stateMachine.state === 'destroyed') {
return resolve(undefined);
}
if (!this.forkProcess) {
this.emitter.emit('task:destroyed');
return resolve(undefined);
}
const timeoutId = setTimeout(() => {
clearTimeout(timeoutId);
this.killFork();
reject(new Error('Destroy operation timed out'));
}, 5000);
const onDestroy = () => {
clearTimeout(timeoutId);
this.off('task:destroyed', onDestroy);
resolve(undefined);
};
this.once('task:destroyed', onDestroy);
this.forkProcess.send({
command: 'task:destroy'
});
});
}
execute() {
return new Promise((resolve, reject) => {
if (!this.forkProcess) {
return reject(new Error('Cannot execute background task because it hasn\'t been started yet. Please initialize the task using the start() method before attempting to execute it.'));
}
const executionId = inlineScheduledTask.createID();
let timeoutId;
if (typeof this.options?.executeTimeout === 'number') {
timeoutId = setTimeout(() => {
cleanupListeners();
reject(new Error('Execution timeout exceeded'));
}, this.options.executeTimeout);
}
const cleanupListeners = () => {
if (timeoutId)
clearTimeout(timeoutId);
this.off('execution:finished', onFinished);
this.off('execution:failed', onFail);
};
const onFinished = (context) => {
if (context.execution?.id !== executionId)
return;
cleanupListeners();
resolve(context.execution?.result);
};
const onFail = (context) => {
if (context.execution?.id !== executionId)
return;
cleanupListeners();
reject(context.execution?.error || new Error('Execution failed without specific error'));
};
this.on('execution:finished', onFinished);
this.on('execution:failed', onFail);
this.forkProcess.send({
command: 'task:execute',
executionId
});
});
}
async handleShouldRun(message) {
let allowed = false;
let error;
try {
allowed = this.runCoordinator ? await this.runCoordinator.shouldRun(message.key, message.ttlMs) : false;
}
catch (err) {
error = err?.message ?? String(err);
}
this.forkProcess?.send({ type: 'coordinator:result', reqId: message.reqId, allowed, error });
}
on(event, fun) {
this.emitter.on(event, fun);
}
off(event, fun) {
this.emitter.off(event, fun);
}
once(event, fun) {
this.emitter.once(event, fun);
}
logEvent(event, context) {
switch (event) {
case 'execution:missed': {
const handled = this.emitter.listenerCount('execution:missed') > 0;
if (!this.suppressMissedWarning && !handled) {
this.logger.warn(`missed execution at ${context.date}! Possible blocking IO or high CPU user at the same process used by node-cron.`);
}
break;
}
case 'execution:overlap':
if (this.options?.noOverlap) {
this.logger.warn('task still running, new execution blocked by overlap prevention!');
}
break;
case 'execution:failed':
if (context.execution?.error) {
this.logger.error(context.execution.error);
}
break;
}
}
createContext(executionDate, execution, reason) {
const localTime = new inlineScheduledTask.LocalizedTime(executionDate, this.options?.timezone);
const ctx = {
date: localTime.toDate(),
dateLocalIso: localTime.toISO(),
triggeredAt: new Date(),
task: this,
execution: execution
};
if (reason)
ctx.reason = reason;
return ctx;
}
}
function serializableOptions(options) {
if (!options)
return options;
const { logger: _logger, runCoordinator: _runCoordinator, ...rest } = options;
return rest;
}
function deserializeError(str) {
const data = JSON.parse(str);
const Err = globalThis[data.name] || Error;
const err = new Err(data.message);
if (data.stack) {
err.stack = data.stack;
}
Object.keys(data).forEach(key => {
if (!['name', 'message', 'stack'].includes(key)) {
err[key] = data[key];
}
});
return err;
}
const moduleFilename = __filename;
const registry = new TaskRegistry();
function schedule(expression, func, options) {
const task = createTask(expression, func, options);
let started;
try {
started = task.start();
}
catch (error) {
registry.remove(task);
throw error;
}
if (started && typeof started.catch === 'function') {
started.catch((error) => {
(options?.logger || inlineScheduledTask.logger).error(`Failed to start scheduled task: ${error?.message ?? error}`);
});
}
return task;
}
function createTask(expression, func, options) {
parse$1(expression);
if (options?.distributed && !options.name) {
throw new Error('`distributed` requires a `name` (it forms the coordination key shared across instances).');
}
let task;
if (func instanceof Function) {
task = new inlineScheduledTask.InlineScheduledTask(expression, func, options);
}
else {
const taskPath = solvePath(func);
task = new BackgroundScheduledTask(expression, taskPath, options);
}
registry.add(task);
return task;
}
function solvePath(filePath) {
if (path.isAbsolute(filePath))
return url.pathToFileURL(filePath).href;
if (filePath.startsWith('file://'))
return filePath;
const stackLines = new Error().stack?.split('\n');
if (stackLines) {
stackLines?.shift();
const callerLine = stackLines?.find((line) => { return line.indexOf(moduleFilename) === -1; });
const match = callerLine?.match(/(file:\/\/)?(((\/?)(\w:))?([/\\].+)):\d+:\d+/);
if (match) {
const dir = `${match[5] ?? ""}${path.dirname(match[6])}`;
return url.pathToFileURL(path.resolve(dir, filePath)).href;
}
}
throw new Error(`Could not locate task file ${filePath}`);
}
function validate(expression) {
try {
validate$1(expression);
return true;
}
catch (e) {
return false;
}
}
const validateDetailed = validateDetailed$1;
const parse = parse$1;
async function shutdown(timeout = 5000) {
const tasks = registry.all();
const pending = [];
for (const task of tasks.values()) {
const wait = new Promise(resolve => {
const onSettled = () => {
task.off('execution:finished', onSettled);
task.off('execution:failed', onSettled);
resolve();
};
task.once('execution:finished', onSettled);
task.once('execution:failed', onSettled);
});
const busy = task.isBusy();
Promise.resolve(task.stop()).catch((error) => {
inlineScheduledTask.logger.error(`Error stopping task "${task.name}" during shutdown: ${error?.message ?? error}`);
});
if (busy) {
pending.push(wait);
}
}
if (pending.length) {
await Promise.race([
Promise.allSettled(pending),
new Promise(r => setTimeout(r, timeout))
]);
}
for (const task of tasks.values()) {
Promise.resolve(task.destroy()).catch((error) => {
inlineScheduledTask.logger.error(`Error destroying task "${task.name}" during shutdown: ${error?.message ?? error}`);
});
}
}
const getTasks = registry.all;
const getTask = registry.get;
const nodeCron = {
schedule,
createTask,
validate,
validateDetailed,
parse,
getTasks,
getTask,
setLogger: inlineScheduledTask.setLogger,
setRunCoordinator: inlineScheduledTask.setRunCoordinator,
shutdown,
};
exports.setLogger = inlineScheduledTask.setLogger;
exports.setRunCoordinator = inlineScheduledTask.setRunCoordinator;
exports.createTask = createTask;
exports.default = nodeCron;
exports.getTask = getTask;
exports.getTasks = getTasks;
exports.nodeCron = nodeCron;
exports.parse = parse;
exports.schedule = schedule;
exports.shutdown = shutdown;
exports.solvePath = solvePath;
exports.validate = validate;
exports.validateDetailed = validateDetailed;
//# sourceMappingURL=node-cron.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"node-cron.cjs","sources":["../src/task-registry.ts","../src/pattern/validation/pattern-validation.ts","../src/tasks/background-scheduled-task/background-scheduled-task.ts","../src/node-cron.ts"],"sourcesContent":[null,null,null,null],"names":["isNthWeekdayToken","validateDetailed","resolveNickname","convertExpression","parse","validate","resolvePath","dirname","EventEmitter","createID","StateMachine","TimeMatcher","logger","resolveRunCoordinator","fork","LocalizedTime","parseExpression","InlineScheduledTask","pathToFileURL","validation","validateDetailedExpression","setLogger","setRunCoordinator"],"mappings":";;;;;;;;;;;AAEA,MAAM,KAAK,GAAG,IAAI,GAAG,EAA0B;MAElC,YAAY,CAAA;AACvB,IAAA,GAAG,CAAC,IAAmB,EAAA;QACrB,IAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,EAAC;YACnB,MA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AAK,CACX,CAAA,EAAG,QAAQ,CAAC,CAAC,CAAC,CAAA,yCAAA,CAA2C,CAC5D;AAELine truncated
+125
View File
@@ -0,0 +1,125 @@
interface Logger {
info(message: string): void;
warn(message: string): void;
error(message: string | Error, err?: Error): void;
debug(message: string | Error, err?: Error): void;
}
declare function setLogger(logger: Logger): void;
interface RunCoordinator {
shouldRun(key: string, ttlMs: number): boolean | Promise<boolean>;
onComplete?(key: string): void | Promise<void>;
}
type SkipReason = 'not-elected' | 'coordinator-error';
declare function setRunCoordinator(coordinator: RunCoordinator | undefined): void;
type TaskContext = {
date: Date;
dateLocalIso: string;
task?: ScheduledTask;
execution?: Execution;
triggeredAt: Date;
reason?: SkipReason;
error?: Error;
};
type TaskEvent = 'task:started' | 'task:stopped' | 'task:destroyed' | 'task:failed' | 'execution:started' | 'execution:finished' | 'execution:failed' | 'execution:missed' | 'execution:overlap' | 'execution:maxReached' | 'execution:skipped';
type TaskOptions = {
timezone?: string;
name?: string;
noOverlap?: boolean;
distributed?: boolean;
runCoordinator?: RunCoordinator;
distributedLease?: number;
maxExecutions?: number;
maxRandomDelay?: number;
logger?: Logger;
suppressMissedWarning?: boolean;
missedExecutionTolerance?: number;
executeTimeout?: number;
startTimeout?: number;
unref?: boolean;
};
type Execution = {
id: string;
reason: 'invoked' | 'scheduled';
startedAt?: Date;
finishedAt?: Date;
error?: Error;
result?: any;
};
type LastRun = {
date: Date;
result?: unknown;
error?: Error;
};
type TaskFn = (context: TaskContext) => any | Promise<any>;
interface ScheduledTask {
id: string;
name?: string;
start(): void | Promise<void>;
stop(): void | Promise<void>;
getStatus(): string;
destroy(): void | Promise<void>;
execute(): Promise<any>;
getNextRun(): Date | null;
getNextRuns(count: number): Date[];
match(date: Date): boolean;
msToNext(): number | null;
isBusy(): boolean;
runsLeft(): number | undefined;
getPattern(): string;
lastRun(): LastRun | null;
unref(): void;
ref(): void;
on(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
off(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
once(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
}
interface CronFieldError {
field: string;
value?: string;
message: string;
}
interface ParsedFields {
second: number[];
minute: number[];
hour: number[];
dayOfMonth: (number | string)[];
month: number[];
dayOfWeek: (number | string)[];
}
interface DetailedValidation {
valid: boolean;
fields?: ParsedFields;
errors: CronFieldError[];
}
declare function validateDetailed$1(pattern: string): DetailedValidation;
declare function parse$1(pattern: string): ParsedFields;
declare function schedule(expression: string, func: TaskFn | string, options?: TaskOptions): ScheduledTask;
declare function createTask(expression: string, func: TaskFn | string, options?: TaskOptions): ScheduledTask;
declare function solvePath(filePath: string): string;
declare function validate(expression: string): boolean;
declare const validateDetailed: typeof validateDetailed$1;
declare const parse: typeof parse$1;
declare function shutdown(timeout?: number): Promise<void>;
declare const getTasks: () => Map<string, ScheduledTask>;
declare const getTask: (taskId: string) => ScheduledTask | undefined;
interface NodeCron {
schedule: typeof schedule;
createTask: typeof createTask;
validate: typeof validate;
validateDetailed: typeof validateDetailed;
parse: typeof parse;
getTasks: typeof getTasks;
getTask: typeof getTask;
setLogger: typeof setLogger;
setRunCoordinator: typeof setRunCoordinator;
shutdown: typeof shutdown;
}
declare const nodeCron: NodeCron;
export { createTask, nodeCron as default, getTask, getTasks, nodeCron, parse, schedule, setLogger, setRunCoordinator, shutdown, solvePath, validate, validateDetailed };
export type { CronFieldError, DetailedValidation, LastRun, Logger, NodeCron, ParsedFields, RunCoordinator, ScheduledTask, SkipReason, TaskContext, TaskFn, TaskOptions };
+125
View File
@@ -0,0 +1,125 @@
interface Logger {
info(message: string): void;
warn(message: string): void;
error(message: string | Error, err?: Error): void;
debug(message: string | Error, err?: Error): void;
}
declare function setLogger(logger: Logger): void;
interface RunCoordinator {
shouldRun(key: string, ttlMs: number): boolean | Promise<boolean>;
onComplete?(key: string): void | Promise<void>;
}
type SkipReason = 'not-elected' | 'coordinator-error';
declare function setRunCoordinator(coordinator: RunCoordinator | undefined): void;
type TaskContext = {
date: Date;
dateLocalIso: string;
task?: ScheduledTask;
execution?: Execution;
triggeredAt: Date;
reason?: SkipReason;
error?: Error;
};
type TaskEvent = 'task:started' | 'task:stopped' | 'task:destroyed' | 'task:failed' | 'execution:started' | 'execution:finished' | 'execution:failed' | 'execution:missed' | 'execution:overlap' | 'execution:maxReached' | 'execution:skipped';
type TaskOptions = {
timezone?: string;
name?: string;
noOverlap?: boolean;
distributed?: boolean;
runCoordinator?: RunCoordinator;
distributedLease?: number;
maxExecutions?: number;
maxRandomDelay?: number;
logger?: Logger;
suppressMissedWarning?: boolean;
missedExecutionTolerance?: number;
executeTimeout?: number;
startTimeout?: number;
unref?: boolean;
};
type Execution = {
id: string;
reason: 'invoked' | 'scheduled';
startedAt?: Date;
finishedAt?: Date;
error?: Error;
result?: any;
};
type LastRun = {
date: Date;
result?: unknown;
error?: Error;
};
type TaskFn = (context: TaskContext) => any | Promise<any>;
interface ScheduledTask {
id: string;
name?: string;
start(): void | Promise<void>;
stop(): void | Promise<void>;
getStatus(): string;
destroy(): void | Promise<void>;
execute(): Promise<any>;
getNextRun(): Date | null;
getNextRuns(count: number): Date[];
match(date: Date): boolean;
msToNext(): number | null;
isBusy(): boolean;
runsLeft(): number | undefined;
getPattern(): string;
lastRun(): LastRun | null;
unref(): void;
ref(): void;
on(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
off(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
once(event: TaskEvent, fun: (context: TaskContext) => Promise<void> | void): void;
}
interface CronFieldError {
field: string;
value?: string;
message: string;
}
interface ParsedFields {
second: number[];
minute: number[];
hour: number[];
dayOfMonth: (number | string)[];
month: number[];
dayOfWeek: (number | string)[];
}
interface DetailedValidation {
valid: boolean;
fields?: ParsedFields;
errors: CronFieldError[];
}
declare function validateDetailed$1(pattern: string): DetailedValidation;
declare function parse$1(pattern: string): ParsedFields;
declare function schedule(expression: string, func: TaskFn | string, options?: TaskOptions): ScheduledTask;
declare function createTask(expression: string, func: TaskFn | string, options?: TaskOptions): ScheduledTask;
declare function solvePath(filePath: string): string;
declare function validate(expression: string): boolean;
declare const validateDetailed: typeof validateDetailed$1;
declare const parse: typeof parse$1;
declare function shutdown(timeout?: number): Promise<void>;
declare const getTasks: () => Map<string, ScheduledTask>;
declare const getTask: (taskId: string) => ScheduledTask | undefined;
interface NodeCron {
schedule: typeof schedule;
createTask: typeof createTask;
validate: typeof validate;
validateDetailed: typeof validateDetailed;
parse: typeof parse;
getTasks: typeof getTasks;
getTask: typeof getTask;
setLogger: typeof setLogger;
setRunCoordinator: typeof setRunCoordinator;
shutdown: typeof shutdown;
}
declare const nodeCron: NodeCron;
export { createTask, nodeCron as default, getTask, getTasks, nodeCron, parse, schedule, setLogger, setRunCoordinator, shutdown, solvePath, validate, validateDetailed };
export type { CronFieldError, DetailedValidation, LastRun, Logger, NodeCron, ParsedFields, RunCoordinator, ScheduledTask, SkipReason, TaskContext, TaskFn, TaskOptions };
+741
View File
@@ -0,0 +1,741 @@
import { r as resolveNickname, c as convertExpression, i as isNthWeekdayToken, a as createID, S as StateMachine, T as TimeMatcher, l as logger, b as resolveRunCoordinator, L as LocalizedTime, s as setRunCoordinator, d as setLogger, I as InlineScheduledTask } from './_shared.js';
import path, { resolve, dirname } from 'path';
import { fileURLToPath, pathToFileURL } from 'url';
import { fork } from 'child_process';
import { EventEmitter } from 'events';
import 'node:crypto';
const tasks = new Map();
class TaskRegistry {
add(task) {
if (this.has(task.id)) {
throw Error(`task ${task.id} already registered!`);
}
tasks.set(task.id, task);
task.on('task:destroyed', () => {
this.remove(task);
});
}
get(taskId) {
return tasks.get(taskId);
}
remove(task) {
if (this.has(task.id)) {
tasks.delete(task.id);
task.destroy();
}
}
all() {
return tasks;
}
has(taskId) {
return tasks.has(taskId);
}
killAll() {
tasks.forEach(id => this.remove(id));
}
}
const validationRegex = /^(?:\d+|\*|\*\/\d+)$/;
const ALLOWED_CHARS_REGEX = /^[a-zA-Z0-9-*/,#? ]+$/;
function splitFields(resolved) {
return resolved.replace(/\s{2,}/g, ' ').trim().split(' ');
}
function isValidExpression(expression, min, max) {
const options = expression;
for (const option of options) {
const optionAsInt = parseInt(option, 10);
if ((!Number.isNaN(optionAsInt) &&
(optionAsInt < min || optionAsInt > max)) ||
!validationRegex.test(option))
return false;
}
return true;
}
function isInvalidSecond(expression) {
return !isValidExpression(expression, 0, 59);
}
function isInvalidMinute(expression) {
return !isValidExpression(expression, 0, 59);
}
function isInvalidHour(expression) {
return !isValidExpression(expression, 0, 23);
}
const DAY_OF_MONTH_W_TOKEN = /^(\d{1,2}|L)W$/i;
const DAY_OF_MONTH_OFFSET_TOKEN = /^L-(\d{1,2})$/i;
function isInvalidDayOfMonth(expression) {
const days = expression.filter((value) => {
if (value === 'L')
return false;
const weekday = DAY_OF_MONTH_W_TOKEN.exec(String(value));
if (weekday) {
if (weekday[1] === 'L')
return false;
const target = parseInt(weekday[1], 10);
return target < 1 || target > 31;
}
const offset = DAY_OF_MONTH_OFFSET_TOKEN.exec(String(value));
if (offset) {
const n = parseInt(offset[1], 10);
return n < 1 || n > 30;
}
return true;
});
return !isValidExpression(days, 1, 31);
}
function hasInvalidWModifier(rawDayOfMonth) {
if (!/w/i.test(rawDayOfMonth))
return false;
return rawDayOfMonth.split(',').some((token) => {
const value = token.trim();
if (!/w/i.test(value))
return false;
return !DAY_OF_MONTH_W_TOKEN.test(value);
});
}
function isInvalidMonth(expression) {
return !isValidExpression(expression, 1, 12);
}
function isInvalidWeekDay(expression) {
const days = expression.filter((value) => !isNthWeekdayToken(value) && !/^[0-7]L$/.test(value));
return !isValidExpression(days, 0, 7);
}
const MAX_DAYS_IN_MONTH = {
1: 31, 2: 29, 3: 31, 4: 30, 5: 31, 6: 30,
7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31,
};
function isImpossibleDayOfMonth(days, months) {
if (days.some((day) => typeof day !== 'number'))
return false;
return !months.some((month) => days.some((day) => day <= MAX_DAYS_IN_MONTH[month]));
}
function validateFields(patterns, executablePatterns) {
if (isInvalidSecond(executablePatterns[0]))
throw new Error(`${patterns[0]} is a invalid expression for second`);
if (isInvalidMinute(executablePatterns[1]))
throw new Error(`${patterns[1]} is a invalid expression for minute`);
if (isInvalidHour(executablePatterns[2]))
throw new Error(`${patterns[2]} is a invalid expression for hour`);
if (isInvalidDayOfMonth(executablePatterns[3]) || hasInvalidWModifier(patterns[3]))
throw new Error(`${patterns[3]} is a invalid expression for day of month`);
if (isInvalidMonth(executablePatterns[4]))
throw new Error(`${patterns[4]} is a invalid expression for month`);
if (isInvalidWeekDay(executablePatterns[5]))
throw new Error(`${patterns[5]} is a invalid expression for week day`);
if (isImpossibleDayOfMonth(executablePatterns[3], executablePatterns[4]))
throw new Error(`${patterns[3]} ${patterns[4]} is an impossible day of month for the given month`);
}
const FIELDS = [
{ key: 'second', label: 'second', invalid: isInvalidSecond },
{ key: 'minute', label: 'minute', invalid: isInvalidMinute },
{ key: 'hour', label: 'hour', invalid: isInvalidHour },
{ key: 'dayOfMonth', label: 'day of month', invalid: isInvalidDayOfMonth },
{ key: 'month', label: 'month', invalid: isInvalidMonth },
{ key: 'dayOfWeek', label: 'week day', invalid: isInvalidWeekDay },
];
function validateDetailed$1(pattern) {
if (typeof pattern !== 'string')
return { valid: false, errors: [{ field: 'expression', message: 'pattern must be a string' }] };
const resolved = resolveNickname(pattern);
if (!ALLOWED_CHARS_REGEX.test(resolved))
return { valid: false, errors: [{ field: 'expression', value: pattern, message: 'pattern includes illegal characters' }] };
const raw = splitFields(resolved);
if (raw.length !== 5 && raw.length !== 6)
return { valid: false, errors: [{ field: 'expression', value: pattern, message: `expected 5 or 6 fields but got ${raw.length}` }] };
const patterns = raw.length === 5 ? ['0', ...raw] : raw;
const executable = convertExpression(pattern);
const errors = [];
FIELDS.forEach((f, i) => {
const rawWMisuse = f.key === 'dayOfMonth' && hasInvalidWModifier(patterns[i]);
if (f.invalid(executable[i]) || rawWMisuse)
errors.push({ field: f.key, value: patterns[i], message: `${patterns[i]} is a invalid expression for ${f.label}` });
});
if (!errors.length && isImpossibleDayOfMonth(executable[3], executable[4])) {
errors.push({
field: 'dayOfMonth',
value: patterns[3],
message: `${patterns[3]} ${patterns[4]} is an impossible day of month for the given month`,
});
}
if (errors.length)
return { valid: false, errors };
return {
valid: true,
errors: [],
fields: {
second: executable[0],
minute: executable[1],
hour: executable[2],
dayOfMonth: executable[3],
month: executable[4],
dayOfWeek: executable[5],
},
};
}
function parse$1(pattern) {
const result = validateDetailed$1(pattern);
if (!result.valid)
throw new Error(result.errors[0].message);
return result.fields;
}
function validate$1(pattern) {
if (typeof pattern !== 'string')
throw new TypeError('pattern must be a string!');
const resolved = resolveNickname(pattern);
if (!ALLOWED_CHARS_REGEX.test(resolved))
throw new TypeError('pattern includes illegal characters!');
const raw = splitFields(resolved);
if (raw.length !== 5 && raw.length !== 6)
throw new Error(`expected 5 or 6 fields but got ${raw.length}`);
const patterns = raw.length === 5 ? ['0', ...raw] : raw;
const executablePatterns = convertExpression(resolved);
validateFields(patterns, executablePatterns);
}
const daemonPath = resolve(dirname(fileURLToPath(import.meta.url)), 'daemon.js');
class TaskEmitter extends EventEmitter {
}
class BackgroundScheduledTask {
emitter;
id;
name;
cronExpression;
taskPath;
options;
forkProcess;
stateMachine;
logger;
suppressMissedWarning;
timeMatcher;
runCount;
runCoordinator;
_lastRun = null;
executing = false;
killPending = false;
pendingKillCleanup;
currentExecution;
killRequested = false;
startPromise;
constructor(cronExpression, taskPath, options) {
this.cronExpression = cronExpression;
this.taskPath = taskPath;
this.options = options;
this.id = createID();
this.name = options?.name || this.id;
this.emitter = new TaskEmitter();
this.stateMachine = new StateMachine('stopped');
this.timeMatcher = new TimeMatcher(cronExpression, options?.timezone);
this.runCount = 0;
this.on('execution:started', (context) => {
if (context?.execution?.reason === 'scheduled')
this.runCount++;
this.executing = true;
this.currentExecution = context?.execution;
});
this.on('execution:finished', (context) => { this.executing = false; this.currentExecution = undefined; this.recordLastRun(context.execution); });
this.on('execution:failed', (context) => { this.executing = false; this.currentExecution = undefined; this.recordLastRun(context.execution); });
this.logger = options?.logger || logger;
this.suppressMissedWarning = options?.suppressMissedWarning || false;
this.runCoordinator = options?.distributed ? resolveRunCoordinator(options?.runCoordinator) : undefined;
this.on('task:stopped', () => {
this.killForkWhenSettled();
if (this.stateMachine.state !== 'destroyed') {
this.stateMachine.changeState('stopped');
}
});
this.on('task:destroyed', () => {
this.killForkWhenSettled();
this.stateMachine.changeState('destroyed');
});
}
getNextRun() {
if (this.stateMachine.state !== 'stopped') {
return this.timeMatcher.getNextMatch(new Date());
}
return null;
}
getNextRuns(count) {
const runs = [];
let from = new Date();
for (let i = 0; i < count; i++) {
from = this.timeMatcher.getNextMatch(from);
runs.push(from);
}
return runs;
}
match(date) {
return this.timeMatcher.match(date);
}
msToNext() {
const next = this.getNextRun();
return next ? next.getTime() - Date.now() : null;
}
isBusy() {
return this.getStatus() === 'running';
}
runsLeft() {
if (this.options?.maxExecutions == null)
return undefined;
return Math.max(0, this.options.maxExecutions - this.runCount);
}
getPattern() {
return this.cronExpression;
}
lastRun() {
return this._lastRun;
}
recordLastRun(execution) {
if (!execution)
return;
const raw = execution.finishedAt ?? execution.startedAt;
const date = raw ? new Date(raw) : new Date();
const lastRun = { date };
if (execution.error) {
lastRun.error = execution.error;
}
else {
lastRun.result = execution.result;
}
this._lastRun = lastRun;
}
killForkWhenSettled() {
if (!this.forkProcess)
return;
if (!this.executing) {
this.killFork();
return;
}
if (this.killPending)
return;
this.killPending = true;
const onSettled = () => this.killFork();
this.once('execution:finished', onSettled);
this.once('execution:failed', onSettled);
this.pendingKillCleanup = () => {
this.off('execution:finished', onSettled);
this.off('execution:failed', onSettled);
};
}
clearPendingKillWait() {
this.pendingKillCleanup?.();
this.pendingKillCleanup = undefined;
this.killPending = false;
}
killFork() {
this.clearPendingKillWait();
this.killRequested = true;
this.forkProcess?.kill();
this.forkProcess = undefined;
}
handleUnexpectedExit(code, signal) {
this.clearPendingKillWait();
const erro = new Error(`daemon exited unexpectedly (code ${code}, signal ${signal})`);
this.logger.error(erro);
if (this.executing) {
const execution = { id: createID(), reason: 'scheduled', ...this.currentExecution, error: erro, finishedAt: new Date() };
this.emitter.emit('execution:failed', this.createContext(new Date(), execution));
}
try {
this.stateMachine.changeState('stopped');
}
catch (err) {
this.logger.error(err);
}
const context = this.createContext(new Date());
context.error = erro;
this.emitter.emit('task:failed', context);
this.forkProcess = undefined;
}
start() {
if (this.stateMachine.state === 'destroyed') {
return Promise.resolve();
}
if (this.startPromise) {
return this.startPromise;
}
if (this.forkProcess) {
return Promise.resolve();
}
this.startPromise = this.forkAndStart().finally(() => {
this.startPromise = undefined;
});
return this.startPromise;
}
forkAndStart() {
return new Promise((resolve, reject) => {
const startTimeout = this.options?.startTimeout ?? 5000;
const failStart = (error) => {
clearTimeout(timeout);
this.killFork();
reject(error);
};
const timeout = setTimeout(() => {
failStart(new Error(`Start operation timed out after ${startTimeout}ms. The background task file may have failed to load or taken too long to import; ` +
`verify it runs on its own and consider increasing the \`startTimeout\` option.`));
}, startTimeout);
this.killRequested = false;
let startSucceeded = false;
try {
this.forkProcess = fork(daemonPath);
this.forkProcess.on('error', (err) => {
failStart(new Error(`Error on daemon: ${err.message}`));
});
this.forkProcess.on('exit', (code, signal) => {
if (this.killRequested) {
this.killRequested = false;
return;
}
if (code !== 0 && signal !== 'SIGTERM') {
if (startSucceeded) {
this.handleUnexpectedExit(code, signal);
return;
}
const erro = new Error(`node-cron daemon exited with code ${code || signal}`);
this.logger.error(erro);
failStart(erro);
}
});
this.forkProcess.on('message', (message) => {
if (message.type === 'coordinator:shouldRun') {
void this.handleShouldRun(message);
return;
}
if (message.type === 'coordinator:complete') {
this.runCoordinator?.onComplete?.(message.key)?.catch?.((err) => this.logger.error('Run coordinator onComplete failed', err));
return;
}
if (message.event === 'daemon:error') {
failStart(message.jsonError ? deserializeError(message.jsonError) : new Error('Background task failed to start'));
return;
}
if (message.jsonError) {
if (message.context?.execution) {
message.context.execution.error = deserializeError(message.jsonError);
delete message.jsonError;
}
}
if (message.context?.task?.state) {
this.stateMachine.changeState(message.context?.task?.state);
}
if (message.context) {
const execution = message.context?.execution;
delete execution?.hasError;
const context = this.createContext(new Date(message.context.date), execution, message.context.reason);
this.logEvent(message.event, context);
this.emitter.emit(message.event, context);
}
});
this.once('task:started', () => {
startSucceeded = true;
this.stateMachine.changeState('idle');
clearTimeout(timeout);
resolve(undefined);
});
this.forkProcess.send({
command: 'task:start',
path: this.taskPath,
cron: this.cronExpression,
options: serializableOptions(this.options)
});
}
catch (error) {
failStart(error);
}
});
}
stop() {
return new Promise((resolve, reject) => {
if (this.stateMachine.state === 'destroyed') {
return resolve(undefined);
}
if (!this.forkProcess) {
this.emitter.emit('task:stopped');
return resolve(undefined);
}
const timeoutId = setTimeout(() => {
clearTimeout(timeoutId);
this.killFork();
reject(new Error('Stop operation timed out'));
}, 5000);
const cleanupAndResolve = () => {
clearTimeout(timeoutId);
this.off('task:stopped', onStopped);
resolve(undefined);
};
const onStopped = () => {
cleanupAndResolve();
};
this.once('task:stopped', onStopped);
this.forkProcess.send({
command: 'task:stop'
});
});
}
getStatus() {
return this.stateMachine.state;
}
unref() {
if (!this.forkProcess)
return;
this.forkProcess.unref();
this.forkProcess.channel?.unref();
}
ref() {
if (!this.forkProcess)
return;
this.forkProcess.ref();
this.forkProcess.channel?.ref();
}
destroy() {
return new Promise((resolve, reject) => {
if (this.stateMachine.state === 'destroyed') {
return resolve(undefined);
}
if (!this.forkProcess) {
this.emitter.emit('task:destroyed');
return resolve(undefined);
}
const timeoutId = setTimeout(() => {
clearTimeout(timeoutId);
this.killFork();
reject(new Error('Destroy operation timed out'));
}, 5000);
const onDestroy = () => {
clearTimeout(timeoutId);
this.off('task:destroyed', onDestroy);
resolve(undefined);
};
this.once('task:destroyed', onDestroy);
this.forkProcess.send({
command: 'task:destroy'
});
});
}
execute() {
return new Promise((resolve, reject) => {
if (!this.forkProcess) {
return reject(new Error('Cannot execute background task because it hasn\'t been started yet. Please initialize the task using the start() method before attempting to execute it.'));
}
const executionId = createID();
let timeoutId;
if (typeof this.options?.executeTimeout === 'number') {
timeoutId = setTimeout(() => {
cleanupListeners();
reject(new Error('Execution timeout exceeded'));
}, this.options.executeTimeout);
}
const cleanupListeners = () => {
if (timeoutId)
clearTimeout(timeoutId);
this.off('execution:finished', onFinished);
this.off('execution:failed', onFail);
};
const onFinished = (context) => {
if (context.execution?.id !== executionId)
return;
cleanupListeners();
resolve(context.execution?.result);
};
const onFail = (context) => {
if (context.execution?.id !== executionId)
return;
cleanupListeners();
reject(context.execution?.error || new Error('Execution failed without specific error'));
};
this.on('execution:finished', onFinished);
this.on('execution:failed', onFail);
this.forkProcess.send({
command: 'task:execute',
executionId
});
});
}
async handleShouldRun(message) {
let allowed = false;
let error;
try {
allowed = this.runCoordinator ? await this.runCoordinator.shouldRun(message.key, message.ttlMs) : false;
}
catch (err) {
error = err?.message ?? String(err);
}
this.forkProcess?.send({ type: 'coordinator:result', reqId: message.reqId, allowed, error });
}
on(event, fun) {
this.emitter.on(event, fun);
}
off(event, fun) {
this.emitter.off(event, fun);
}
once(event, fun) {
this.emitter.once(event, fun);
}
logEvent(event, context) {
switch (event) {
case 'execution:missed': {
const handled = this.emitter.listenerCount('execution:missed') > 0;
if (!this.suppressMissedWarning && !handled) {
this.logger.warn(`missed execution at ${context.date}! Possible blocking IO or high CPU user at the same process used by node-cron.`);
}
break;
}
case 'execution:overlap':
if (this.options?.noOverlap) {
this.logger.warn('task still running, new execution blocked by overlap prevention!');
}
break;
case 'execution:failed':
if (context.execution?.error) {
this.logger.error(context.execution.error);
}
break;
}
}
createContext(executionDate, execution, reason) {
const localTime = new LocalizedTime(executionDate, this.options?.timezone);
const ctx = {
date: localTime.toDate(),
dateLocalIso: localTime.toISO(),
triggeredAt: new Date(),
task: this,
execution: execution
};
if (reason)
ctx.reason = reason;
return ctx;
}
}
function serializableOptions(options) {
if (!options)
return options;
const { logger: _logger, runCoordinator: _runCoordinator, ...rest } = options;
return rest;
}
function deserializeError(str) {
const data = JSON.parse(str);
const Err = globalThis[data.name] || Error;
const err = new Err(data.message);
if (data.stack) {
err.stack = data.stack;
}
Object.keys(data).forEach(key => {
if (!['name', 'message', 'stack'].includes(key)) {
err[key] = data[key];
}
});
return err;
}
const moduleFilename = fileURLToPath(import.meta.url);
const registry = new TaskRegistry();
function schedule(expression, func, options) {
const task = createTask(expression, func, options);
let started;
try {
started = task.start();
}
catch (error) {
registry.remove(task);
throw error;
}
if (started && typeof started.catch === 'function') {
started.catch((error) => {
(options?.logger || logger).error(`Failed to start scheduled task: ${error?.message ?? error}`);
});
}
return task;
}
function createTask(expression, func, options) {
parse$1(expression);
if (options?.distributed && !options.name) {
throw new Error('`distributed` requires a `name` (it forms the coordination key shared across instances).');
}
let task;
if (func instanceof Function) {
task = new InlineScheduledTask(expression, func, options);
}
else {
const taskPath = solvePath(func);
task = new BackgroundScheduledTask(expression, taskPath, options);
}
registry.add(task);
return task;
}
function solvePath(filePath) {
if (path.isAbsolute(filePath))
return pathToFileURL(filePath).href;
if (filePath.startsWith('file://'))
return filePath;
const stackLines = new Error().stack?.split('\n');
if (stackLines) {
stackLines?.shift();
const callerLine = stackLines?.find((line) => { return line.indexOf(moduleFilename) === -1; });
const match = callerLine?.match(/(file:\/\/)?(((\/?)(\w:))?([/\\].+)):\d+:\d+/);
if (match) {
const dir = `${match[5] ?? ""}${path.dirname(match[6])}`;
return pathToFileURL(path.resolve(dir, filePath)).href;
}
}
throw new Error(`Could not locate task file ${filePath}`);
}
function validate(expression) {
try {
validate$1(expression);
return true;
}
catch (e) {
return false;
}
}
const validateDetailed = validateDetailed$1;
const parse = parse$1;
async function shutdown(timeout = 5000) {
const tasks = registry.all();
const pending = [];
for (const task of tasks.values()) {
const wait = new Promise(resolve => {
const onSettled = () => {
task.off('execution:finished', onSettled);
task.off('execution:failed', onSettled);
resolve();
};
task.once('execution:finished', onSettled);
task.once('execution:failed', onSettled);
});
const busy = task.isBusy();
Promise.resolve(task.stop()).catch((error) => {
logger.error(`Error stopping task "${task.name}" during shutdown: ${error?.message ?? error}`);
});
if (busy) {
pending.push(wait);
}
}
if (pending.length) {
await Promise.race([
Promise.allSettled(pending),
new Promise(r => setTimeout(r, timeout))
]);
}
for (const task of tasks.values()) {
Promise.resolve(task.destroy()).catch((error) => {
logger.error(`Error destroying task "${task.name}" during shutdown: ${error?.message ?? error}`);
});
}
}
const getTasks = registry.all;
const getTask = registry.get;
const nodeCron = {
schedule,
createTask,
validate,
validateDetailed,
parse,
getTasks,
getTask,
setLogger,
setRunCoordinator,
shutdown,
};
export { createTask, nodeCron as default, getTask, getTasks, nodeCron, parse, schedule, setLogger, setRunCoordinator, shutdown, solvePath, validate, validateDetailed };
//# sourceMappingURL=node-cron.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"node-cron.js","sources":["../src/task-registry.ts","../src/pattern/validation/pattern-validation.ts","../src/tasks/background-scheduled-task/background-scheduled-task.ts","../src/node-cron.ts"],"sourcesContent":[null,null,null,null],"names":["validateDetailed","parse","validate","resolvePath","parseExpression","validation","validateDetailedExpression"],"mappings":";;;;;;;AAEA,MAAM,KAAK,GAAG,IAAI,GAAG,EAA0B;MAElC,YAAY,CAAA;AACvB,IAAA,GAAG,CAAC,IAAmB,EAAA;QACrB,IAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,EAAC;YACnB,MAAM,KAAK,CAAC,CAAA,KAAA,EAAQ,IAAI,CAAC,EAAE,CAAA,oBAAA,CAAsB,CAAC;QACpD;QAEA,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC;AAExB,QAAA,IAAI,CAAC,EAAE,CAAC,gBAAgB,EAAE,MAAK;AAC7B,YAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC;AACnB,QAAA,CAAC,CAAC;IACJ;AAEA,IAAA,GAAG,CAAC,MAAc,EAAA;AAChB,QAAA,OAAO,K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Q,CAAC,CAAC,CAAC,CAAA,qCAAA,CAAuC,Line truncated
+90
View File
@@ -0,0 +1,90 @@
{
"name": "node-cron",
"version": "4.6.0",
"description": "Job scheduling for Node.js with overlap prevention, distributed coordination, and background tasks. Zero dependencies, written in TypeScript.",
"author": "Lucas Merencia",
"license": "ISC",
"homepage": "https://nodecron.com",
"type": "module",
"main": "./dist/node-cron.cjs",
"module": "./dist/node-cron.js",
"types": "./dist/node-cron.d.ts",
"exports": {
".": {
"import": {
"types": "./dist/node-cron.d.ts",
"default": "./dist/node-cron.js"
},
"require": {
"types": "./dist/node-cron.d.cts",
"default": "./dist/node-cron.cjs"
}
}
},
"scripts": {
"test": "vitest run --coverage",
"test:watch": "vitest",
"lint": "./node_modules/.bin/eslint ./src",
"typecheck": "tsc --noEmit",
"check": "npm run lint && npm test",
"build": "rollup -c",
"dev": "rollup -c -w",
"prepack": "npm run build"
},
"engines": {
"node": ">=20"
},
"files": [
"dist/"
],
"publishConfig": {
"access": "public",
"provenance": true
},
"repository": {
"type": "git",
"url": "git+https://github.com/node-cron/node-cron.git"
},
"keywords": [
"cron",
"crontab",
"cronjob",
"node-cron",
"scheduler",
"task-scheduler",
"job-scheduler",
"schedule",
"scheduled-tasks",
"task",
"job",
"typescript",
"nodejs",
"background-jobs",
"distributed-cron",
"overlap-prevention",
"cron-jobs"
],
"bugs": {
"url": "https://github.com/node-cron/node-cron/issues"
},
"devDependencies": {
"@eslint/js": "^9.26.0",
"@rollup/plugin-commonjs": "^29.0.3",
"@rollup/plugin-node-resolve": "^16.0.3",
"@rollup/plugin-replace": "^6.0.3",
"@rollup/plugin-typescript": "^12.3.0",
"@types/expect": "^1.20.4",
"@types/node": "^22.15.3",
"@typescript-eslint/eslint-plugin": "^8.32.0",
"@typescript-eslint/parser": "^8.32.0",
"@vitest/coverage-v8": "^4.1.9",
"eslint": "^10.5.0",
"globals": "^16.1.0",
"rollup": "^4.62.0",
"rollup-plugin-dts": "^6.4.1",
"tslib": "^2.8.1",
"typescript": "^5.8.3",
"typescript-eslint": "^8.32.0",
"vitest": "^4.1.9"
}
}