krontab 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +329 -2
- package/dist/index.cjs +764 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +76 -0
- package/dist/index.d.mts +77 -0
- package/dist/index.mjs +734 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +73 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 [Kasukabe Tsumugi]
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,330 @@
|
|
|
1
|
-
#
|
|
1
|
+
# krontab
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A minimal, JS-native crontab.
|
|
4
|
+
|
|
5
|
+
Drop a script in a directory, write a 5-field cron expression in its header comment, and the runner will spawn it when the expression matches — once per minute, nothing more.
|
|
6
|
+
|
|
7
|
+
No retries, no catch-up runs, no overlap protection, no process supervision. If a job ran or not, read the log.
|
|
8
|
+
|
|
9
|
+
The name is a nod to `crontab` with a `K` — meaning both "kron" (time) and the author's initial. The package still exports one function, `cronjob()`; if you are upgrading from `cronjob-js`, the only changes are the package name, the import specifier, and the lock name (see [Permissions](#permissions)).
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pnpm add krontab
|
|
15
|
+
# or
|
|
16
|
+
npm i krontab
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Requires **Node.js >= 22.14.0**.
|
|
20
|
+
|
|
21
|
+
## Quick start
|
|
22
|
+
|
|
23
|
+
Valid cron expression:
|
|
24
|
+
|
|
25
|
+
```text
|
|
26
|
+
* * * * *
|
|
27
|
+
┬ ┬ ┬ ┬ ┬
|
|
28
|
+
│ │ │ │ │
|
|
29
|
+
│ │ │ │ └─ day of week (0-7, 1L-7L) (0 or 7 is Sun)
|
|
30
|
+
│ │ │ └────── month (1-12, JAN-DEC)
|
|
31
|
+
│ │ └─────────── day of month (1-31, L)
|
|
32
|
+
│ └──────────────── hour (0-23)
|
|
33
|
+
└───────────────────── minute (0-59)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Create a job script:
|
|
37
|
+
|
|
38
|
+
```js
|
|
39
|
+
// cronjob/backup.js
|
|
40
|
+
// @cron 0 3 * * * # 每天凌晨三点
|
|
41
|
+
console.log('backup', new Date().toISOString());
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Start the runner from your project root:
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
// main.js
|
|
48
|
+
import { cronjob } from 'krontab';
|
|
49
|
+
|
|
50
|
+
const task = await cronjob({ dir: './cronjob' });
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Then let pm2 keep it alive:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
pm2 start main.js --name cronjob --log cronjob-runner/main.log --no-treekill
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
> **Keep `--no-treekill`.** pm2 kills the whole process tree by default. Jobs are spawned detached and unref'd, but they are still in pm2's tree, so `pm2 restart` / `pm2 stop` would kill a job that is still running — with no `[EXIT]` line, because the runner exits first. With `--no-treekill` (or `treekill: false` in an ecosystem file) running jobs survive a deploy. The runner is also a single-instance daemon: start it in fork mode, not with `-i` (see below).
|
|
60
|
+
|
|
61
|
+
`cronjob()` resolves to a controller with `stop()` / `pause()` / `resume()`.
|
|
62
|
+
|
|
63
|
+
To see what would run without starting the scheduler, pass `--list` (or `-l`) to the same script:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
node main.js --list
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
That prints one line per schedule and exits, before the single-instance lock is taken:
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
2026/11/22 03:00:00.000 0 3 * * * backup.js /usr/bin/node backup.js
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The four columns are **next run time** (formatted with `timezone`), **expression** (block members are indented and marked `[group]`), **path relative to `dir`**, and the command that will be spawned. `--list` goes through the same `write`, so the usual `[INFO] Config loaded: …` line appears before the table. Rows follow glob order (roughly alphabetical within a directory); they are not sorted by next run time.
|
|
76
|
+
|
|
77
|
+
Files with no `@cron` line are reported with `[WARN] No cron expression: <path>` instead of a row. An expression that parses but has no next occurrence prints `(no next run)` in the time column; one that fails to parse at this stage prints `(invalid)`. In practice extraction only keeps expressions that already parsed, so a malformed line is dropped earlier and never reaches the table. When nothing is found at all, `[INFO] No scripts found in <dir>` is printed and the command exits.
|
|
78
|
+
|
|
79
|
+
`--list` is checked by scanning `process.argv` in `cronjob()`, so any argument list containing `--list` or `-l` takes this branch — including one meant for your own program. Do not forward those flags.
|
|
80
|
+
|
|
81
|
+
## Writing jobs
|
|
82
|
+
|
|
83
|
+
The cron expression goes in the **header comment** — from line 1 until the first line of real code. For `.ts`/`.js` use `//` or `/** */`, for `.sh` use `#`. Blank lines and other comment lines inside that header are fine; they do not end it. In a `/* */` block every body line must start with `*` — that is the conventional style (and what most editors and formatters produce). A `/*` block whose body has no `*` prefix is **not** a header: the first such line ends it, so no `@cron` is seen and the file is silently not scheduled.
|
|
84
|
+
|
|
85
|
+
`@cronbegin` / `@cronend` are matched **anywhere in a header line**, including prose. A comment that merely mentions them (`` // see @cronend ``) is treated as the marker, so the file is rejected with a block error rather than scheduled. This is deliberate: a file that fails to parse never runs, which is safer than guessing what the author meant. Keep those words out of notes inside a header.
|
|
86
|
+
|
|
87
|
+
`@cronutc` is `@cron` with the same 5-field expression, but the expression is matched in **UTC** instead of `timezone`. It is a per-line marker: it applies only to the line it is on and does not change how other lines are matched. Use it when a schedule must not shift with daylight saving time:
|
|
88
|
+
|
|
89
|
+
```js
|
|
90
|
+
// @cron 0 9 * * * 每天九点(按 timezone)
|
|
91
|
+
// @cronutc 0 9 * * * 每天 09:00 UTC
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Everything after the 5 fields is still a note, and `@cronutc` works inside `@cronbegin` / `@cronend` blocks like any other line. `--list` marks those rows with a `UTC` prefix.
|
|
95
|
+
|
|
96
|
+
Both markers are found anywhere in the line, notes included, so a header line must not contain `@cronutc` unless it is that line's marker. Putting both markers on one line (`// @cron 0 9 * * * 也可以写成 @cronutc`) is ambiguous — the line is rejected with an `[ERROR]` and not scheduled. Keep `@cronutc` out of the note.
|
|
97
|
+
|
|
98
|
+
For `.py` the header may use `#` comments. A `@cron` must sit on one of the `#` lines; the `'''` / `"""` docstring delimiters are accepted in the header but **docstring body lines are not scanned**, so `@cron` inside a multi-line docstring is ignored. Use `# @cron …` for Python jobs.
|
|
99
|
+
|
|
100
|
+
```js
|
|
101
|
+
// @cron 0 9 * * *
|
|
102
|
+
// @cron 30 18 * * 1-5 工作日下班
|
|
103
|
+
console.log('two independent schedules in one file');
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
#!/bin/bash
|
|
108
|
+
# @cron */5 * * * *
|
|
109
|
+
echo "every five minutes"
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Rules:
|
|
113
|
+
|
|
114
|
+
- Only the **5-field** form is supported: `minute hour day-of-month month day-of-week`.
|
|
115
|
+
- The first 5 whitespace-separated tokens after `@cron` are the expression; everything after them is a human-readable note and is ignored.
|
|
116
|
+
- Lines without `@cron` are ignored silently.
|
|
117
|
+
- Field syntax is [cron-parser](https://github.com/harrisiirak/cron-parser)'s: ranges, lists, steps, and names such as `MON-FRI` in the day-of-week field.
|
|
118
|
+
- Aliases like `@daily` or `@hourly` are **not** accepted — they are not 5-field expressions.
|
|
119
|
+
|
|
120
|
+
The marker does not have to be at the start of the line: `// 说明 @cron 0 9 * * *` works, and the text before the marker is ignored.
|
|
121
|
+
|
|
122
|
+
### A note on trailing words
|
|
123
|
+
|
|
124
|
+
Because the note is whatever follows the 5 fields, a **6th token that cron-parser can read** makes the line look like a seconds-level expression, so it is rejected:
|
|
125
|
+
|
|
126
|
+
```js
|
|
127
|
+
// @cron 0 9 * * * 1 ← parses as a 6-field (seconds) cron → error, not scheduled
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The check is: take the first 6 tokens and try to parse them. If that succeeds, the line is skipped with `6 fields cron is not supported, use 5 fields instead`. If it fails, the first 5 tokens are scheduled and everything after is the note. So anything cron-parser cannot resolve as a field works as a note:
|
|
131
|
+
|
|
132
|
+
```js
|
|
133
|
+
// @cron 0 9 * * * 每天 ← Chinese note, 6-token parse fails → 5 fields + note
|
|
134
|
+
// @cron 0 9 * * * # 1 ← "#" is not a field → 5 fields + note
|
|
135
|
+
// @cron 0 9 * * * - 1 ← same
|
|
136
|
+
// @cron 0 9 * * * extra words ← "extra" is not an alias → 5 fields + note
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Multiple schedules in one file
|
|
140
|
+
|
|
141
|
+
Each `@cron` line schedules independently — if two lines match in the same minute, the script is spawned twice:
|
|
142
|
+
|
|
143
|
+
```js
|
|
144
|
+
// @cron 0 9 * * *
|
|
145
|
+
// @cron 0 21 * * *
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Use a block when you want "either of these, but only once":
|
|
149
|
+
|
|
150
|
+
```js
|
|
151
|
+
// @cronbegin
|
|
152
|
+
// @cron 0 9 * * 1-5
|
|
153
|
+
// @cron 0 9 * * 6
|
|
154
|
+
// @cronend
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
A block spawns the file **once** when any line inside it matches. Blocks are numbered in the order they appear, and each block counts independently — two blocks that both match in the same minute spawn the file twice. Lines outside any block are ungrouped and each schedules independently.
|
|
158
|
+
|
|
159
|
+
`@cronbegin` and `@cronend` must each be alone on their line. A line is classified in this order — begin, then end, then expression — so `@cronbegin @cron 0 9 * * *` opens a block and **drops the expression on that line**; put them on separate lines. Nested or unclosed blocks, and an `@cronend` without a matching begin, cause the whole file to be skipped and an error to be logged. A line inside a block that has no `@cron` marker triggers a `[WARN]`, since it is probably a comment that was meant to be a schedule.
|
|
160
|
+
|
|
161
|
+
### Second-level expressions are not supported
|
|
162
|
+
|
|
163
|
+
Six-field expressions are **not** supported:
|
|
164
|
+
|
|
165
|
+
```js
|
|
166
|
+
// @cron 0 0 9 * * * ← rejected, error logged, not scheduled
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
The runner logs an error and skips that line — it will not silently reinterpret it as a 5-field expression. Fewer than 5 fields (`@cron 0 9 * *`) is rejected the same way, with an error; cron-parser would otherwise pad the missing field.
|
|
170
|
+
|
|
171
|
+
## Supported script types
|
|
172
|
+
|
|
173
|
+
| Extension | Interpreter |
|
|
174
|
+
| ---------------- | ------------------------------------------------------ |
|
|
175
|
+
| `.js` / `.mjs` / `.cjs` | the current Node.js (`process.execPath`) |
|
|
176
|
+
| `.ts` / `.mts` / `.cts` | `tsx` → `ts-node` → Node.js with native type stripping |
|
|
177
|
+
| `.sh` | `bash`, falling back to `sh` |
|
|
178
|
+
| `.py` | `python3` → `python` (only if added to `include`) |
|
|
179
|
+
|
|
180
|
+
`.mjs` / `.cjs` / `.mts` / `.cts` are only picked up if you add them to `include` (the default glob is `**/*.{ts,js,sh}`); their header comments use the same `//` and `/** */` rules as `.js` / `.ts`.
|
|
181
|
+
|
|
182
|
+
Extensions with no interpreter mapping are only reached if a script is extracted with one; in practice an unknown extension has no comment syntax for its header, so no `@cron` line is found and nothing is spawned. Such a job would log `[WARN] path=… unsupported extension` if it ever got that far.
|
|
183
|
+
|
|
184
|
+
If a `.ts` file has a `#!` line, that shebang wins over the default interpreter. Same for any other extension. The shebang is parsed as `command args...`, so `#!/usr/bin/env node` runs `/usr/bin/env node <script>` and `#!/bin/bash -e` runs `/bin/bash -e <script>`.
|
|
185
|
+
|
|
186
|
+
If `tsx` is not installed, `.ts` still runs under Node.js directly, but not every TypeScript syntax is supported — a warning is logged at startup.
|
|
187
|
+
|
|
188
|
+
`.py` is only used if you add it to `include`; the default glob does not match it.
|
|
189
|
+
|
|
190
|
+
## Logs
|
|
191
|
+
|
|
192
|
+
Everything goes to the runner's stdout (use `pm2 --log` to persist it) plus a per-job log file:
|
|
193
|
+
|
|
194
|
+
- **Runner log**: one line per event — `[INFO]`, `[WARN]`, `[ERROR]`, `[SPAWN]`, `[EXIT]`, `[DEBUG]`. The three job lifecycle lines are:
|
|
195
|
+
|
|
196
|
+
```
|
|
197
|
+
2026/11/21 09:00:00.017 [SPAWN] path=daily/report.js pid=12345
|
|
198
|
+
2026/11/21 09:00:04.210 [EXIT] path=daily/report.js pid=12345 code=0 signal=null
|
|
199
|
+
2026/11/21 09:00:00.018 [ERROR] path=daily/report.js pid=-1 Error: spawn ENOENT
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
`[ERROR]` uses `pid=-1` when the process never started.
|
|
203
|
+
- **Timestamps** are `yyyy/MM/dd HH:mm:ss.SSS` in `timezone` (that is `zh-CN` `Intl.DateTimeFormat` output).
|
|
204
|
+
- **Job log**: `<logDir>/<relative-path>.log`, appended, with the `.log` suffix after the full filename (`daily/report.js` → `<logDir>/daily/report.js.log`). Each job's own stdout/stderr goes here; the pid is only in the runner log.
|
|
205
|
+
- **Debug**: a `[DEBUG] Start` / `[DEBUG] Finished in Nms` pair wraps each tick that found at least one script. If `dir` has no matching scripts the runner logs `[INFO] No scripts found.` instead and skips the pair.
|
|
206
|
+
|
|
207
|
+
`path` in the runner log is always relative to `dir`.
|
|
208
|
+
|
|
209
|
+
Replace `write` to send the runner log somewhere else (a file, a logger, pm2's stdout). It receives the tag already formatted as `[INFO]` etc.:
|
|
210
|
+
|
|
211
|
+
```js
|
|
212
|
+
await cronjob({
|
|
213
|
+
dir: './cronjob',
|
|
214
|
+
write(tag, ...args) {
|
|
215
|
+
myLogger.log(tag, ...args);
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
## API
|
|
221
|
+
|
|
222
|
+
### `cronjob(config?): Promise<TaskController>`
|
|
223
|
+
|
|
224
|
+
Starts the minute-based scheduler. Immediately takes a single-instance lock keyed by a hash of `dir` — a second runner on the same directory throws `krontab already running`. The lock is an abstract Unix socket, so the OS releases it when the process dies, including `SIGKILL`.
|
|
225
|
+
|
|
226
|
+
If `process.argv` contains `--list` or `-l`, `cronjob()` prints the schedule table and calls `process.exit(0)` instead of starting the scheduler. No lock is taken in that branch.
|
|
227
|
+
|
|
228
|
+
### Permissions
|
|
229
|
+
|
|
230
|
+
On startup `cronjob()` checks that `dir` and `logDir` are owned by the current user and are **not group- or world-writable**, and throws rather than starting if not. Directories it creates itself are made with mode `0755` regardless of umask, so they pass that check on `umask 002` machines (Debian/Ubuntu with `USERGROUPS_ENAB`) as well as `022` ones. Both directories are equivalent to code execution as the runner's user — anyone who can write `dir` can drop a script, and anyone who can write `logDir` can append to job logs. `/tmp`-style shared directories are rejected by design. Custom log files are created with mode `0640`; existing files are appended to without changing their mode. The check is skipped when running as root (root can write anywhere, so it proves nothing) and on platforms without `process.getuid` (Windows).
|
|
231
|
+
|
|
232
|
+
The check covers **`dir` and `logDir` themselves only** — it does not walk up to their parents and does not re-check subdirectories:
|
|
233
|
+
|
|
234
|
+
- A world-writable **parent** passes: with `/srv/shared` at `777` containing `jobs` at `755`, another user can rename `jobs` away and put their own directory in its place.
|
|
235
|
+
- A world-writable **subdirectory** inside `dir` passes: `dir/team` at `777` still lets `team/x.js` be globbed and spawned.
|
|
236
|
+
|
|
237
|
+
Deciding what is safe to scan is left to deployment: keep `dir` and everything below it writable by the runner's user only.
|
|
238
|
+
|
|
239
|
+
The lock name is derived from `dir`, so it is predictable; any local process that binds that abstract socket first will make the runner report `krontab already running`. That is a local denial of service at worst — it cannot be used to make the runner execute anything.
|
|
240
|
+
|
|
241
|
+
> **Upgrading from `cronjob-js`:** the lock name changed from `cronjob-js-…` to `krontab-…`. If an old runner is still running on the same `dir`, a new one will **not** detect it and both will schedule. Stop the old process before starting the new one.
|
|
242
|
+
|
|
243
|
+
### `UserCronjobConfig`
|
|
244
|
+
|
|
245
|
+
| Option | Type | Default | Description |
|
|
246
|
+
| ---------- | ------------------------------------------ | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
247
|
+
| `dir` | `string` | `process.cwd()` | Directory scanned for job scripts. Created if missing. |
|
|
248
|
+
| `logDir` | `string` | same as `dir` | Where per-job logs are written. Created if missing. |
|
|
249
|
+
| `include` | `string[]` | `['**/*.{ts,js,sh}']` | Glob patterns for job scripts (passed to `fs.glob`). Add `'**/*.py'` if you use Python. |
|
|
250
|
+
| `exclude` | `string[]` | see below | Glob patterns to skip (passed to `fs.glob` as `exclude`). |
|
|
251
|
+
| `timezone` | `string` | `'Asia/Shanghai'` | IANA timezone used for cron matching and for the `timeFormat` timestamps. See [Daylight saving time](#daylight-saving-time). |
|
|
252
|
+
| `jobcwd` | `string \| (scriptPath: string) => string` | same as `dir` | Working directory for spawned jobs. Pass a function to derive it per script. |
|
|
253
|
+
| `write` | `(tag: Tag, ...args: any[]) => void` | `console.log(time, tag, ...args)` | Where runner log lines go. `tag` is one of `[INFO]` `[WARN]` `[ERROR]` `[SPAWN]` `[EXIT]` `[DEBUG]`. The default writes to stdout with a timestamp in `timezone`. |
|
|
254
|
+
|
|
255
|
+
Invalid config throws a `TypeError` naming the option (`dir`, `logDir`, `include`, …); an unknown `timezone` throws a `RangeError` from `Intl.DateTimeFormat`.
|
|
256
|
+
|
|
257
|
+
#### Daylight saving time
|
|
258
|
+
|
|
259
|
+
Matching uses the wall clock in `timezone`. In a DST zone that means:
|
|
260
|
+
|
|
261
|
+
- The repeated hour after a fall-back runs matching jobs **twice** (for example `30 1 * * *` in `America/New_York` on 2026-11-01, at both 01:30 EDT and 01:30 EST).
|
|
262
|
+
- The missing hour after a spring-forward runs them **not at all** (for example `30 2 * * *` on 2026-03-08 in `America/New_York`).
|
|
263
|
+
|
|
264
|
+
This is the opposite of vixie/Debian `cron`, whose man page says jobs skipped by a forward jump "will be run soon after the change" and jobs in the repeated hour "will not be re-run". If exact DST behaviour matters, schedule in a zone without DST (UTC is the obvious choice). The default `Asia/Shanghai` has no DST.
|
|
265
|
+
|
|
266
|
+
#### Default `exclude`
|
|
267
|
+
|
|
268
|
+
```js
|
|
269
|
+
[
|
|
270
|
+
'**/node_modules/',
|
|
271
|
+
'**/.git/',
|
|
272
|
+
'**/.vscode/',
|
|
273
|
+
'**/.claude/',
|
|
274
|
+
'**/__pycache__/',
|
|
275
|
+
'**/dist/',
|
|
276
|
+
'**/dist-tsc/',
|
|
277
|
+
'**/coverage/',
|
|
278
|
+
];
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
`**/` matters: a plain `'node_modules/'` only matches the directory at the root of `dir`, so a vendored sub-project under `jobs/node_modules/` would still be scanned and read every minute. Dot-directories (`.git`, `.vscode`, `.claude`) are skipped by `fs.glob` anyway; they are listed so that an explicit `exclude` override cannot accidentally re-include them. `dist`, `dist-tsc` and `coverage` are common build outputs that would otherwise be globbed and read as job scripts.
|
|
282
|
+
|
|
283
|
+
If you replace `exclude`, you replace this whole list — there is no merging.
|
|
284
|
+
|
|
285
|
+
### `TaskController`
|
|
286
|
+
|
|
287
|
+
```ts
|
|
288
|
+
interface TaskController {
|
|
289
|
+
stop(): void; // clears the pending timer, sets state to Stopped; resume() is a no-op after this
|
|
290
|
+
pause(): void; // the timer keeps ticking but the callback is not run
|
|
291
|
+
resume(): void; // resumes a paused runner
|
|
292
|
+
}
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
## How it works
|
|
296
|
+
|
|
297
|
+
Every minute the runner:
|
|
298
|
+
|
|
299
|
+
1. globs `dir` for matching files,
|
|
300
|
+
2. reads the header comment block of each file,
|
|
301
|
+
3. parses the `@cron` lines with `cron-parser`, using `timezone`,
|
|
302
|
+
4. spawns matching scripts, detached and unref'd, with stdout/stderr redirected to their log file.
|
|
303
|
+
|
|
304
|
+
There is no in-memory cache: files are re-read and re-parsed every minute, so editing a script's `@cron` line takes effect on the next tick without a restart.
|
|
305
|
+
|
|
306
|
+
The first tick is aligned to the next minute boundary. If the timer fires a few milliseconds early (common on WSL), it waits for the boundary instead of running the same minute twice.
|
|
307
|
+
|
|
308
|
+
The next tick is scheduled before the current one runs, so a slow file read or a throwing job does not break the chain. An exception or rejected promise from the tick is logged as one `[ERROR] Task tick failed:` line and nothing else — the next minute proceeds normally.
|
|
309
|
+
|
|
310
|
+
At startup the runner also warns about a missing `tsx` (only matters for `.ts`) and reports whether `python3`/`python` was found (only matters if you included `.py`).
|
|
311
|
+
|
|
312
|
+
## Design limits
|
|
313
|
+
|
|
314
|
+
These are deliberate, not missing features:
|
|
315
|
+
|
|
316
|
+
- **No retries.** A failed job stays failed until its next scheduled run.
|
|
317
|
+
- **No catch-up.** If the machine was down at 03:00, the 03:00 job does not run when it comes back.
|
|
318
|
+
- **No overlap protection.** A long job will overlap with its next run.
|
|
319
|
+
- **No process management.** Jobs are detached; the runner does not watch or kill them.
|
|
320
|
+
- **No exit-code alerts.** Non-zero exits are logged; read the job log if you care.
|
|
321
|
+
- **No job lifecycle hooks.** There is no callback for "job started" or "job finished"; the log lines are the only signal.
|
|
322
|
+
- **The timer is minute-aligned, not second-aligned.** If the process is busy or the host is suspended across a boundary, the tick happens when the event loop gets to it, and there is no catch-up for the missed minute.
|
|
323
|
+
|
|
324
|
+
The runner itself is kept alive by pm2. If the runner dies, nothing runs until pm2 restarts it.
|
|
325
|
+
|
|
326
|
+
Run it in pm2 **fork mode** (the default). With `-i` (cluster mode) every worker shares one task directory; the single-instance lock lets only the first worker schedule, and the others exit with `krontab already running` and are restarted by pm2 in a loop.
|
|
327
|
+
|
|
328
|
+
## License
|
|
329
|
+
|
|
330
|
+
MIT — see [LICENSE](LICENSE).
|