krontab 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +329 -2
- package/dist/index.cjs +8 -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 +8 -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).
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("node:perf_hooks"),l=require("node:path"),u=require("node:fs"),d=require("node:process"),f=require("cron-parser"),p=require("node:fs/promises"),m=require("node:child_process"),h=require("node:crypto"),g=require("node:net");l=s(l,1),u=s(u,1),g=s(g,1);let _;(function(e){e.CRON=`@cron`,e.REGEX=/@cron\b/,e.BEGIN=`@cronbegin`,e.BEGIN_REGEX=/@cronbegin\b/,e.END=`@cronend`,e.END_REGEX=/@cronend\b/,e.UTC=`@cronutc`,e.UTC_REGEX=/@cronutc\b/})(_||={});const v=e=>e.includes(`/`)||e.includes(`\\`);function y(e){if(v(e))return(0,u.existsSync)(e)?e:null;for(let t of(d.env.PATH||`/usr/local/bin:/usr/bin:/bin`).split(l.delimiter))if(t&&(0,u.existsSync)((0,l.join)(t,e)))return e;return null}function b(){let e=y(`tsx`)??y(`ts-node`)??process.execPath,t=e=>({cmd:e,args:[]}),n={".ts":t(e),".mts":t(e),".cts":t(e),".js":t(process.execPath),".mjs":t(process.execPath),".cjs":t(process.execPath),".py":{cmd:y(`python3`)||y(`python`)||`none`,args:[]},".sh":{cmd:y(`bash`)||`sh`,args:[]},none:{cmd:`none`,args:[]}};return{interpreters:n,hasTsx:e!==process.execPath,pythonCmd:n[`.py`].cmd}}function x(e,t){return e.interpreters[t]||e.interpreters.none}function S(e){return{info:(...t)=>e(`[INFO]`,...t),err:(...t)=>e(`[ERROR]`,...t),warn:(...t)=>e(`[WARN]`,...t),spawn:(...t)=>e(`[SPAWN]`,...t),exit:(...t)=>e(`[EXIT]`,...t),debug:(...t)=>e(`[DEBUG]`,...t)}}function C(e){return(t,...n)=>console.log(e.format(/* @__PURE__ */ new Date),t,...n)}const w={include:[`**/*.{ts,js,sh}`],exclude:[`**/node_modules/`,`**/.git/`,`**/.vscode/`,`**/.claude/`,`**/__pycache__/`,`**/dist/`,`**/dist-tsc/`,`**/coverage/`],timezone:`Asia/Shanghai`},T=e=>new Intl.DateTimeFormat(`zh-CN`,{year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,fractionalSecondDigits:3,hour12:!1,timeZone:e});function E(e,t=b()){let{dir:n=process.cwd(),logDir:r=n,jobcwd:i=n,include:a=w.include,exclude:o=w.exclude,timezone:s=w.timezone,write:c}=Object(e);if(typeof n!=`string`)throw TypeError("`dir` must be a string");if(typeof r!=`string`)throw TypeError("`logDir` must be a string");if(typeof i!=`string`&&typeof i!=`function`)throw TypeError("`jobcwd` must be a string or a function");if(c!==void 0&&typeof c!=`function`)throw TypeError("`write` must be a function");if(new Intl.DateTimeFormat(`en-US`,{timeZone:s}),!Array.isArray(a)||a.some(e=>typeof e!=`string`))throw TypeError("`include` must be an array of strings");if(!Array.isArray(o)||o.some(e=>typeof e!=`string`))throw TypeError("`exclude` must be an array of strings");let u=(0,l.resolve)(n),d=(0,l.resolve)(r),f=T(s),p=typeof i!=`function`&&i===n?u:i,m=typeof p==`function`?p:()=>p,h=c===void 0?C(f):c;return{dir:u,logDir:d,jobcwd:m,include:a,exclude:o,timezone:s,timeFormat:f,runtime:t,jobState:0,jobTimer:null,write:h,log:S(h)}}const D=e=>{try{return u.default.globSync(e.include,{cwd:e.dir,exclude:e.exclude}).map(t=>l.default.resolve(e.dir,t))}catch(t){return e.log.err(`Error while globbing scripts.`,t),null}},O=e=>{let t=new Date(e.getTime()+6e4);return t.setSeconds(0,0),t};function k(e,t){let n=()=>{if(e.jobState===2)return;let r=/* @__PURE__ */ new Date,i=O(r);e.jobTimer=setTimeout(()=>{if(e.jobTimer=null,e.jobState===2)return;
|
|
2
|
+
//! 定时器可能早于边界触发,相当于等了但还没等到呢,再等一会
|
|
3
|
+
if(e.jobState===1||Date.now()<i.getTime()){n();return}let r=/* @__PURE__ */ new Date;r.setSeconds(0,0),n();try{let n=t(r);n&&typeof n.catch==`function`&&n.catch(t=>e.log.err(`Task tick failed:`,t))}catch(t){e.log.err(`Task tick failed:`,t)}},i.getTime()-r.getTime())};return n(),{stop(){e.jobTimer&&=(clearTimeout(e.jobTimer),null),e.jobState=2},pause(){e.jobState===0&&(e.jobState=1)},resume(){e.jobState!==2&&(e.jobState=0,e.jobTimer===null&&n())}}}const A=(e,t,n,r=e.timezone)=>{try{return f.CronExpressionParser.parse(t,{tz:r,hashSeed:n})}catch{return null}};function j(e,t){return e.includesDate(t)}const M=e=>e.startsWith(`//`)||e.startsWith(`/*`)||e.startsWith(`*`)||e.startsWith(`*/`)||e.length===0,N={".ts":M,".mts":M,".cts":M,".js":M,".mjs":M,".cjs":M,".py":e=>/^(#|'''|""")/.test(e)||e.length===0,".sh":e=>e.startsWith(`#`)||e.length===0};function P(e){return N[e]||(()=>!1)}const F=e=>{let[t,...n]=e.split(/\s+/).filter(Boolean);return t?{cmd:t,args:n}:null},I=e=>e.startsWith(`#!`)?F(e.slice(2)):null;function L(e,t,n,r){if(t.search(_.BEGIN_REGEX)!==-1)return _.BEGIN;if(t.search(_.END_REGEX)!==-1)return _.END;let i=t.search(_.REGEX),a=t.search(_.UTC_REGEX);if(i!==-1&&a!==-1)return e.log.err(`Line contains both ${_.CRON} and ${_.UTC}, nothing scheduled: ${r}`),null;let o=e.timezone,s=-1;if(i===-1?a!==-1&&(o=`UTC`,s=a+_.UTC.length):s=i+_.CRON.length,s===-1)return n&&e.log.warn(`@cron should be used to mark cron expressions in cron blocks: ${r}`),null;let c=t.slice(s).split(/\s+/).filter(Boolean);
|
|
4
|
+
//! 阻止cron-parser 把 4 段自动补齐成另一条合法表达式
|
|
5
|
+
if(c.length<5)return e.log.err(`Invalid cron expression: "${c.join(` `)}" in file: ${r}`),null;if(c.length>=6){let t=c.slice(0,6).join(` `);if(A(e,t,r,o))return e.log.err(`6 fields cron is not supported, use 5 fields instead. Found "${t}" in file: ${r}`),null}let l=A(e,c.slice(0,5).join(` `),r,o);return l?{cron:l,timezone:o}:null}function R(e,t,n){let r=(0,l.extname)(t),i=P(r),a=n.split(`
|
|
6
|
+
`).map(e=>e.trim());if(a.length===0)return null;let o=I(a[0]);if(o&&a.shift(),a.length===0)return null;let s=a.findIndex(e=>!i(e));if(s!==-1&&(a=a.slice(0,s)),a.length===0)return null;let c=[],u=(0,l.relative)(e.dir,t),d=!1,f=0;for(let t of a){let n=L(e,t,d,u);if(n){if(n===_.BEGIN){if(d)return e.log.err(`Nested ${_.BEGIN} found in file: ${u}`),null;f++,d=!0}else if(n===_.END){if(!d)return e.log.err(`${_.END} didn't match ${_.BEGIN} in file: ${u}`),null;d=!1}else c.push({...n,group:d?f:0})}}return d?(e.log.err(`Unclosed ${_.BEGIN}/${_.END} block in file: ${u}`),null):{flatCronGroups:c,interpreter:o??x(e.runtime,r),filepath:t}}const z=65536;async function B(e,t,n){let r=await(0,p.stat)(t);if(!r.isFile())return e.log.warn(`Skipped non-regular file: ${l.default.relative(e.dir,t)}`),null;if(r.size<65536)return await(0,p.readFile)(t,`utf8`);let i=await(0,p.open)(t,`r`);try{let r=Buffer.alloc(z),{bytesRead:a}=await i.read(r,0,z,0),o=r.subarray(0,a).toString(`utf8`);return a===65536&&o.split(`
|
|
7
|
+
`).every(e=>n(e.trim()))&&e.log.warn(`Header longer than ${z} bytes, truncated: ${l.default.relative(e.dir,t)}`),o}finally{await i.close()}}async function V(e,t){let n=[];for(let r=0;r<t.length;r+=100){let i=t.slice(r,r+100).map(async t=>{try{return{filepath:t,content:await B(e,t,P(l.default.extname(t))),error:null}}catch(e){return{filepath:t,content:null,error:e}}}),a=await Promise.all(i);n.push(...a)}return n}function H(e,t,n){let r=0,i=/* @__PURE__ */ new Set;for(let e=0;e<t.flatCronGroups.length;e++){let a=t.flatCronGroups[e];a.group===0&&j(a.cron,n)?r++:!i.has(a.group)&&j(a.cron,n)&&(r++,i.add(a.group))}return{filepath:t.filepath,interpreter:t.interpreter,count:r}}function U(e,t,n){let r=[];for(let i=0;i<t.length;i++){let a=t[i];if(a.error){e.log.err(`Error loading file ${l.default.relative(e.dir,a.filepath)}: ${a.error}`);continue}if(a.content===null)continue;let o=R(e,a.filepath,a.content);if(!o)continue;let s=H(e,o,n);s.count>0&&r.push(s)}return r}const W=e=>{e.runtime.hasTsx||e.log.warn(`'tsx' not found, .ts files will be run by node directly. Not all nodejs versions supports this.`)},G=e=>{e.runtime.pythonCmd===`none`?e.log.warn(`python not available, .py jobs will be ignored`):e.log.info(`python available, .py files will be run by ${e.runtime.pythonCmd}`)},K=e=>{(0,u.mkdirSync)(e.dir,{recursive:!0,mode:493}),e.dir!==e.logDir&&(0,u.mkdirSync)(e.logDir,{recursive:!0,mode:493})},q=e=>{if(typeof process.getuid==`function`&&process.getuid()!==0)for(let[t,n]of[[`dir`,e.dir],[`logDir`,e.logDir]]){let{mode:e,uid:r}=(0,u.statSync)(n),i=!!(e&18);if(r!==process.getuid()||i)throw Error(`${t} must be owned by the current user and not group/world-writable: ${n} (owner=${r}, mode=${(e&511).toString(8)})`)}},J=e=>{try{return(0,u.realpathSync)(e)}catch{return(0,l.resolve)(e)}},Y=e=>new Promise((t,n)=>{let r=`\0krontab-`+(0,h.createHash)(`sha1`).update(J(e.dir)).digest(`hex`).slice(0,8),i=g.default.createServer();i.once(`error`,e=>{n(e.code===`EADDRINUSE`?/* @__PURE__ */ Error(`krontab already running`):e)}),i.listen({path:r,exclusive:!0},()=>{i.unref(),t()})}),X=async e=>{await Y(e),K(e),q(e),W(e),G(e)};function Z(e,{filepath:t,interpreter:n}){let r=null,i=()=>{r!==null&&(u.default.closeSync(r),r=null)},a=l.default.relative(e.dir,t);try{let o=l.default.join(e.logDir,a+`.log`);if(u.default.mkdirSync(l.default.dirname(o),{recursive:!0}),n.cmd===`none`){e.log.warn(`path=${a} unsupported extension`);return}let s=n.cmd,c=n.args.concat(t);r=u.default.openSync(o,`a`,416);let f=(0,m.spawn)(s,c,{stdio:[`ignore`,r,r],detached:!0,env:d.env,cwd:e.jobcwd(t)});f.on(`error`,t=>{i(),e.log.err(`path=${a} pid=${f.pid??`-1`}`,t)}),f.on(`spawn`,()=>{i(),e.log.spawn(`path=${a} pid=${f.pid??`-1`}`)}),f.on(`exit`,(t,n)=>{i(),e.log.exit(`path=${a} pid=${f.pid??`-1`} code=${t} signal=${n}`)}),f.unref()}catch(t){i(),e.log.err(`path=${a} pid=-1`,t)}}async function Q(e){let t=D(e);if(!t)return;if(t.length===0){e.log.info(`No scripts found in ${e.dir}`);return}let n=await V(e,t);for(let t of n){let n=l.default.relative(e.dir,t.filepath);if(t.error){e.log.err(`Error loading file ${n}: ${t.error}`);continue}if(t.content===null)continue;let r=R(e,t.filepath,t.content);if(!r)continue;if(r.flatCronGroups.length===0){e.log.warn(`No cron expression: ${n}`);continue}let i=[r.interpreter.cmd,...r.interpreter.args,n].join(` `);for(let{cron:a,group:o,timezone:s}of r.flatCronGroups){let r=a.stringify(),c=$(e,r,t.filepath,s),l=(o>0?` [${o}] `:``)+(s===`UTC`?`UTC `:``);console.log(`${c.padEnd(24)} ${(l+r).padEnd(18)} ${n.padEnd(32)} ${i}`)}}}function $(e,t,n,r){let i=A(e,t,n,r);if(!i)return`(invalid)`;try{return e.timeFormat.format(i.next().toDate())}catch{return`(no next run)`}}exports.cronjob=async function(e){let t=E(e);t.log.info(`Config loaded: ${JSON.stringify(t)}`),(process.argv.includes(`--list`)||process.argv.includes(`-l`))&&(await Q(t),process.exit(0)),await X(t);let n=k(t,async e=>{let n=D(t);if(!n)return;if(n.length===0){t.log.info(`No scripts found.`);return}let r=c.performance.now();t.log.debug(`Start`);let i=await V(t,n),a=await U(t,i,e);if(t.jobState!==2){for(let e=0;e<a.length;e++)for(let n=0;n<a[e].count;n++)t.jobState===0&&Z(t,a[e]);t.log.debug(`Finished in ${(c.performance.now()-r).toFixed(6)}ms`)}});return t.log.info(`Cronjob start! pid=${process.pid}`),n};
|
|
8
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["existsSync","env","delimiter","join","resolve","fs","path","CronExpressionParser","extname","relative","stat","path","readFile","open","path","mkdirSync","statSync","realpathSync","resolve","createHash","net","fs","path","spawn","env","path","performance","__create","__defProp","__getOwnPropDesc","__getOwnPropNames","__getProtoOf","__hasOwnProp","__copyProps","to","from","except","desc","keys","i","n","key","k","__toESM","mod","isNodeMode","target","node_perf_hooks","node_path","node_fs","node_process","cron_parser","node_fs_promises","node_child_process","node_crypto","node_net","Marker","_Marker","isPath","cmd","detectCommand","dir","detectRuntime","tsCmd","jsLike","interpreters","getDefaultInterpreter","runtime","ext","createLogger","write","args","defaultWrite","formatter","tag","DEFAULTS","createFormatter","timezone","createContext","rawConfig","logDir","jobcwd","include","exclude","pattern","absDir","absLogDir","timeFormat","defaultJobcwd","jobcwdFn","writer","tryGlobSync","cx","v","e","nextMinuteBoundary","next","runTask","fn","schedule","now","nextMinute","noSecondDate","ret","parseExp","exp","filepath","matches","expression","d","jstsAllow","line","allows","getAllowFn","parse","text","getShebang","extractCron","trimmedLine","inBlock","relativePath","index","utcIndex","expStart","tokens","sixExpStr","cron","getJobItem","content","allowFn","lines","shebang","firstNotAllowedIndex","list","inCronBlock","group","extracted","MAX_HEADER","readHeader","allowLine","s","fh","buf","bytesRead","loadFiles","filepaths","result","promises","error","r","getMatchedJob","item","count","set","job","getJobs","files","jobs","f","jobItem","orTsx","orPython","ensureDir","checkDirPermissions","name","mode","uid","writableByOthers","lockKeyOf","acquireLock","resolve","reject","LOCK_NAME","server","initialize","run","interpreter","output","closeOutput","logfile","child","code","signal","invocation","nextRunText","prefix","parsed","config","task","performanceNow"],"sources":["../src/consts.ts","../src/context/interpreter.ts","../src/context/logger.ts","../src/context/index.ts","../src/utils.ts","../src/cron/task.ts","../src/cron/parse.ts","../src/syntax/allow.ts","../src/syntax/shebang.ts","../src/syntax/extract.ts","../src/syntax/header.ts","../src/syntax/job.ts","../src/initialize.ts","../src/run.ts","../src/list.ts","../src/index.ts"],"sourcesContent":["export const enum Tag {\n Info = '[INFO]',\n Spawn = '[SPAWN]',\n Error = '[ERROR]',\n Warn = '[WARN]',\n Exit = '[EXIT]',\n Debug = '[DEBUG]',\n}\n\n/**\n * runner 自己建的目录统一按 0755 创建。\n * - 不能沿用 umask:Debian/Ubuntu 的 USERGROUPS_ENAB 默认 umask 002,mkdir 会建出 775,\n * 紧接着被 checkDirPermissions 拒绝,第一次部署就起不来(F44)\n * - 0755 本身不带 group/other 写位,任何 umask 下都只会更收紧,不会更宽松\n */\nexport const DIR_MODE = 0o755;\n\nexport const enum CronjobState {\n Running,\n Paused,\n Stopped,\n}\n\nexport namespace Marker {\n export const CRON = '@cron' as const;\n export const REGEX = /@cron\\b/;\n\n export const BEGIN = '@cronbegin' as const;\n export const BEGIN_REGEX = /@cronbegin\\b/;\n export const END = '@cronend' as const;\n export const END_REGEX = /@cronend\\b/;\n\n /** 行内标记:`@cronutc <5 段>`,只让这一条按 UTC 解析 */\n export const UTC = '@cronutc' as const;\n export const UTC_REGEX = /@cronutc\\b/;\n}\n\nexport type CronBlockMaker = typeof Marker.BEGIN | typeof Marker.END;\n","import type { Interpreter } from '../types/global.js';\nimport { existsSync } from 'node:fs';\nimport { delimiter, join } from 'node:path';\nimport { env } from 'node:process';\n\nconst isPath = (cmd: string) => cmd.includes('/') || cmd.includes('\\\\');\n\n/**\n * 检测系统中可用的运行时命令。\n * - 只查 PATH、不执行命令:`tsx --version` 实测约 740ms,而探测在 cronjob() 的启动路径上,\n * 每个 cx 都要付一次太贵。代价是\"存在但跑不起来\"的命令会被当成可用,启动时不会发现。\n * - 含路径分隔符的命令直接看文件是否存在,不查 PATH\n * - PATH 为空时(某些 pm2 配置)回退到常见系统目录\n * @returns 可用的命令名,都不可用则返回 null\n */\nexport function detectCommand(cmd: string): string | null {\n if (isPath(cmd)) {\n return existsSync(cmd) ? cmd : null;\n }\n for (const dir of (env.PATH || '/usr/local/bin:/usr/bin:/bin').split(delimiter)) {\n if (dir && existsSync(join(dir, cmd))) {\n return cmd;\n }\n }\n return null;\n}\n\n/** 标记\"没有可用解释器\"的占位命令,run() 见到它只记 WARN 不 spawn */\nexport const CMD_NONE = 'none';\n\n/**\n * 探测所有运行时,返回解释器映射表。\n */\nexport function detectRuntime() {\n const tsCmd = detectCommand('tsx') ?? detectCommand('ts-node') ?? process.execPath;\n const jsLike = (cmd: string): Interpreter => ({ cmd, args: [] });\n\n const interpreters: Record<string, Interpreter> = {\n '.ts': jsLike(tsCmd),\n '.mts': jsLike(tsCmd),\n '.cts': jsLike(tsCmd),\n '.js': jsLike(process.execPath),\n '.mjs': jsLike(process.execPath),\n '.cjs': jsLike(process.execPath),\n '.py': {\n cmd: detectCommand('python3') || detectCommand('python') || CMD_NONE,\n args: [],\n },\n '.sh': {\n cmd: detectCommand('bash') || 'sh',\n args: [],\n },\n none: {\n cmd: CMD_NONE,\n args: [],\n },\n };\n\n return {\n interpreters,\n hasTsx: tsCmd !== process.execPath,\n pythonCmd: interpreters['.py'].cmd,\n };\n}\n\nexport type Runtime = ReturnType<typeof detectRuntime>;\n\n/** 取扩展名对应的解释器;没有映射的(或映射成 none)交给 run() 记 WARN */\nexport function getDefaultInterpreter(runtime: Runtime, ext: string): Interpreter {\n return runtime.interpreters[ext] || runtime.interpreters.none;\n}\n","import type { CronjobLogger } from '../types/global.js';\nimport type { UserCronjobConfig } from '../types/config.js';\nimport { Tag } from '../consts.js';\n\n/**\n * 把 cx.write 包装成带 tag 的方法。\n * - write 是唯一的输出出口,消费者可以整条替换(默认写 stdout)\n */\nexport function createLogger(write: UserCronjobConfig['write']): CronjobLogger {\n return {\n info: (...args: any[]) => write(Tag.Info, ...args),\n err: (...args: any[]) => write(Tag.Error, ...args),\n warn: (...args: any[]) => write(Tag.Warn, ...args),\n spawn: (...args: any[]) => write(Tag.Spawn, ...args),\n exit: (...args: any[]) => write(Tag.Exit, ...args),\n debug: (...args: any[]) => write(Tag.Debug, ...args),\n };\n}\n\n/** 默认输出:`<dtm> <TAG> <内容>`,dtm 用 cx.timezone */\nexport function defaultWrite(formatter: Intl.DateTimeFormat): UserCronjobConfig['write'] {\n return (tag: Tag, ...args: any[]) => console.log(formatter.format(new Date()), tag, ...args);\n}\n","import type { CronjobContext, UserCronjobConfig } from '../types/config.js';\nimport type { Runtime } from './interpreter.js';\nimport { resolve } from 'node:path';\n\nimport { CronjobState } from '../consts.js';\nimport { detectRuntime } from './interpreter.js';\nimport { createLogger, defaultWrite } from './logger.js';\n\n/** 默认值:只改一处,测试与 createContext 都从这里断言 */\nexport const DEFAULTS = {\n include: ['**/*.{ts,js,sh}'],\n exclude: [\n '**/node_modules/',\n '**/.git/',\n '**/.vscode/',\n '**/.claude/',\n '**/__pycache__/',\n '**/dist/',\n '**/dist-tsc/',\n '**/coverage/',\n ],\n timezone: 'Asia/Shanghai',\n};\n\nconst createFormatter = (timezone: string) =>\n new Intl.DateTimeFormat('zh-CN', {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n fractionalSecondDigits: 3,\n hour12: false,\n timeZone: timezone,\n });\n\n/**\n * 创建上下文:配置校验 + 默认值 + 格式化器 + logger + 运行时映射,一次给齐。\n * - `runtime` 由调用方传入时直接用(便于测试注入);不传就现场探测一次\n * - 探测只查 PATH(见 interpreter.ts),不执行外部命令\n */\nexport function createContext(rawConfig?: Partial<UserCronjobConfig>, runtime: Runtime = detectRuntime()): CronjobContext {\n const {\n dir = process.cwd(),\n logDir = dir,\n jobcwd = dir,\n include = DEFAULTS.include,\n exclude = DEFAULTS.exclude,\n timezone = DEFAULTS.timezone,\n write,\n } = Object(rawConfig) as UserCronjobConfig;\n\n if (typeof dir !== 'string') {\n throw new TypeError('`dir` must be a string');\n }\n\n if (typeof logDir !== 'string') {\n throw new TypeError('`logDir` must be a string');\n }\n\n if (typeof jobcwd !== 'string' && typeof jobcwd !== 'function') {\n throw new TypeError('`jobcwd` must be a string or a function');\n }\n\n if (write !== undefined && typeof write !== 'function') {\n throw new TypeError('`write` must be a function');\n }\n\n // Validate timezone by attempting to create a DateTimeFormat with it\n new Intl.DateTimeFormat('en-US', { timeZone: timezone });\n\n if (!Array.isArray(include) || include.some((pattern) => typeof pattern !== 'string')) {\n throw new TypeError('`include` must be an array of strings');\n }\n if (!Array.isArray(exclude) || exclude.some((pattern) => typeof pattern !== 'string')) {\n throw new TypeError('`exclude` must be an array of strings');\n }\n\n // 统一成绝对路径:单例锁的 key、日志相对路径、glob 的 cwd 都依赖它。\n // 否则 './g'、'/abs/g'、'/abs/g/' 会被当成三个不同的任务目录。\n const absDir = resolve(dir);\n const absLogDir = resolve(logDir);\n\n const timeFormat = createFormatter(timezone);\n\n // jobcwd 是字符串时包装成函数;显式传入的(含默认的 dir)不额外改动\n const defaultJobcwd = typeof jobcwd !== 'function' && jobcwd === dir ? absDir : jobcwd;\n const jobcwdFn = typeof defaultJobcwd === 'function' ? defaultJobcwd : () => defaultJobcwd;\n\n const writer = write === undefined ? defaultWrite(timeFormat) : write;\n\n return {\n dir: absDir,\n logDir: absLogDir,\n jobcwd: jobcwdFn,\n include,\n exclude,\n timezone,\n timeFormat,\n runtime,\n jobState: CronjobState.Running,\n jobTimer: null,\n write: writer,\n log: createLogger(writer),\n };\n}\n","import type { CronjobContext } from './types/config.js';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * 返回要处理的文件的绝对路径\n */\nexport const tryGlobSync = (cx: CronjobContext) => {\n try {\n return fs.globSync(cx.include, { cwd: cx.dir, exclude: cx.exclude }).map((v) => path.resolve(cx.dir, v));\n } catch (e) {\n cx.log.err(`Error while globbing scripts.`, e);\n return null;\n }\n};\n\n/**\n * 用来解决超时问题\n * - 不一定用得上\n */\nexport function nolater<T extends Promise<any>>(cx: CronjobContext, promise: T, ms: number = 2000): T {\n const timeout = new Promise<never>((_, reject) => {\n const id = setTimeout(() => {\n clearTimeout(id);\n reject(new Error(`Promise did not resolve within ${ms}ms`));\n }, ms);\n });\n return Promise.race([promise, timeout]) as T;\n}\n","import type { CronjobContext } from '../types/config.js';\nimport { CronjobState } from '../consts.js';\n\nexport interface TaskController {\n /** 停止调度:清掉还没触发的定时器,状态置为 Stopped */\n stop: () => void;\n /** 暂停:定时器继续走,但到点不执行 */\n pause: () => void;\n /** 恢复 */\n resume: () => void;\n}\n\n/** 下一分钟边界(本地毫秒截断到分钟) */\nconst nextMinuteBoundary = (from: Date) => {\n const next = new Date(from.getTime() + 60000);\n next.setSeconds(0, 0);\n return next;\n};\n\n/**\n * 每分钟执行一次 fn,返回控制对象\n * - 状态全部放在 cx.jobState / cx.jobTimer 里,本函数不持有模块级状态\n * - 每次调度都重新读 cx.jobState,因此 stop/resume 在任意时刻都生效\n */\nexport function runTask(cx: CronjobContext, fn: (now: Date) => void | Promise<void>): TaskController {\n const schedule = () => {\n // 只有 Stopped 才停链;Paused 也要继续排,否则进程会在下一个边界自行退出\n if (cx.jobState === CronjobState.Stopped) {\n return;\n }\n\n const now = new Date();\n const nextMinute = nextMinuteBoundary(now);\n\n cx.jobTimer = setTimeout(() => {\n // 定时器已经触发,句柄作废;stop 时靠它判断是否还有待触发的定时器\n cx.jobTimer = null;\n\n // 到点时状态可能已经变了(stop)\n if (cx.jobState === CronjobState.Stopped) {\n return;\n }\n\n // 暂停期间定时器照常走,只是不执行;否则事件循环会空掉,进程在下一个分钟边界自行退出\n if (cx.jobState === CronjobState.Paused) {\n schedule();\n return;\n }\n\n //! 定时器可能早于边界触发,相当于等了但还没等到呢,再等一会\n if (Date.now() < nextMinute.getTime()) {\n schedule();\n return;\n }\n\n const noSecondDate = new Date();\n noSecondDate.setSeconds(0, 0);\n\n // 先排下一轮:fn 抛错或异步 reject 都不能打断调度链(否则整条链就断了)\n schedule();\n\n try {\n const ret = fn(noSecondDate);\n // 只用一条 Error 记录,不重试、不告警,等下一分钟即可\n if (ret && typeof ret.catch === 'function') {\n ret.catch((e) => cx.log.err(`Task tick failed:`, e));\n }\n } catch (e) {\n cx.log.err(`Task tick failed:`, e);\n }\n }, nextMinute.getTime() - now.getTime());\n };\n\n schedule();\n\n return {\n stop() {\n if (cx.jobTimer) {\n clearTimeout(cx.jobTimer);\n cx.jobTimer = null;\n }\n cx.jobState = CronjobState.Stopped;\n },\n pause() {\n if (cx.jobState === CronjobState.Running) {\n cx.jobState = CronjobState.Paused;\n }\n },\n resume() {\n if (cx.jobState === CronjobState.Stopped) {\n return;\n }\n cx.jobState = CronjobState.Running;\n // 暂停期间定时器没有停,所以这里只需要恢复状态即可;\n // 但如果定时器已经被外部清掉(jobTimer === null),重新排一次\n if (cx.jobTimer === null) {\n schedule();\n }\n },\n };\n}\n","import { type CronExpression, CronExpressionParser } from 'cron-parser';\nimport type { CronjobContext } from '../types/config.js';\n\n/**\n * 非得要try很奇怪,但这是官方推荐的方式\n *\n * @param timezone cron 语义使用的时区;默认是 cx.timezone,`@cronutc` 之后传 'UTC'\n */\nexport const parseExp = (\n cx: CronjobContext,\n exp: string,\n filepath: string,\n timezone: string = cx.timezone,\n): CronExpression | null => {\n try {\n return CronExpressionParser.parse(exp, { tz: timezone, hashSeed: filepath });\n } catch {\n return null;\n }\n};\n\n/**\n * 判断给定日期是否匹配 cron 表达式\n * @param expression cron 表达式\n * @param d 待匹配的日期\n */\nexport function matches(expression: CronExpression, d: Date) {\n // & 已经在task里面完成了这一步:d.setSeconds(0, 0);\n return expression.includesDate(d);\n}\n","/**\n * ! 多行注释以`*`开头是实时标准和社区、行业规范\n */\nconst jstsAllow = (line) =>\n // 单行注释\n line.startsWith('//') ||\n // 多行注释\n line.startsWith('/*') ||\n // 多行注释的第二行\n line.startsWith('*') ||\n // 多行注释的最后一行\n line.startsWith('*/') ||\n // 什么都没有,也可能是多行注释\n line.length === 0;\n\nconst allows = {\n '.ts': jstsAllow,\n '.mts': jstsAllow,\n '.cts': jstsAllow,\n '.js': jstsAllow,\n '.mjs': jstsAllow,\n '.cjs': jstsAllow,\n '.py': (line: string) => /^(#|'''|\"\"\")/.test(line) || line.length === 0,\n '.sh': (line: string) => line.startsWith('#') || line.length === 0,\n};\n\nexport function getAllowFn(ext: string): (line: string) => boolean {\n return allows[ext] || (() => false);\n}\n","import type { Interpreter } from '../types/global.js';\n\nconst parse = (text: string): Interpreter | null => {\n const [cmd, ...args] = text.split(/\\s+/).filter(Boolean);\n return cmd ? { cmd, args } : null;\n};\n\n/**\n * 获取解释器,同时也可用于判定是否存在 shebang\n * - 如果有人只是在第一行写了\"#!\",后面没写任何东西,这里也会返回`null`\n */\nexport const getShebang = (line: string) => (line.startsWith('#!') ? parse(line.slice(2)) : null);\n","import type { CronExpression } from 'cron-parser';\nimport type { CronGroupItem, JobItem } from '../types/global.js';\nimport type { CronjobContext } from '../types/config.js';\n\nimport { extname, relative } from 'node:path';\nimport { type CronBlockMaker, Marker } from '../consts.js';\nimport { parseExp } from '../cron/parse.js';\nimport { getDefaultInterpreter } from '../context/interpreter.js';\nimport { getAllowFn } from './allow.js';\nimport { getShebang } from './shebang.js';\n\n/**\n * 一行解析出来的调度:表达式 + 它实际使用的时区。\n * 时区只在这里决定一次,调用方不要再对整行做第二次标记搜索(F45)。\n */\nexport interface ExtractedCron {\n cron: CronExpression;\n timezone: string;\n}\n\n/**\n * 从一行文本中提取带标记的 cron 表达式\n * - 只接受5位表达式,不支持秒级\n * - `@cronutc <5 段>` 是行内指令:这一条按 UTC 解析,不影响其它行\n *\n * @param trimmedLine 已经去掉前导空格的行文本\n * @param inBlock 是否在 @cronbegin 和 @cronend 块中\n * @param relativePath 相对路径,用于日志输出\n */\nexport function extractCron(\n cx: CronjobContext,\n trimmedLine: string,\n inBlock: boolean,\n relativePath: string,\n): ExtractedCron | CronBlockMaker | null {\n if (trimmedLine.search(Marker.BEGIN_REGEX) !== -1) {\n return Marker.BEGIN;\n }\n if (trimmedLine.search(Marker.END_REGEX) !== -1) {\n return Marker.END;\n }\n\n // @cron的index\n const index = trimmedLine.search(Marker.REGEX);\n // @cronutc的index\n const utcIndex = trimmedLine.search(Marker.UTC_REGEX);\n\n // 同一行两个标记无法判断该按哪个时区跑;宁可拒绝并记 Error,也不猜\n if (index !== -1 && utcIndex !== -1) {\n cx.log.err(`Line contains both ${Marker.CRON} and ${Marker.UTC}, nothing scheduled: ${relativePath}`);\n return null;\n }\n\n let timezone = cx.timezone;\n let expStart = -1;\n\n // 一般都是这个,所以这个排前面,分支预测更好\n if (index !== -1) {\n expStart = index + Marker.CRON.length;\n } else if (utcIndex !== -1) {\n timezone = 'UTC';\n expStart = utcIndex + Marker.UTC.length;\n }\n\n if (expStart === -1) {\n if (inBlock) {\n cx.log.warn(`@cron should be used to mark cron expressions in cron blocks: ${relativePath}`);\n }\n return null;\n }\n\n // 直接切片,从标记后面开始获取字符\n const tokens = trimmedLine.slice(expStart).split(/\\s+/).filter(Boolean);\n\n //! 阻止cron-parser 把 4 段自动补齐成另一条合法表达式\n if (tokens.length < 5) {\n cx.log.err(`Invalid cron expression: \"${tokens.join(' ')}\" in file: ${relativePath}`);\n return null;\n }\n\n // 前 6 段能解析说明写的是秒级定时,本项目只支持 5 段,整行不调度\n if (tokens.length >= 6) {\n const sixExpStr = tokens.slice(0, 6).join(' ');\n if (parseExp(cx, sixExpStr, relativePath, timezone)) {\n cx.log.err(`6 fields cron is not supported, use 5 fields instead. Found \"${sixExpStr}\" in file: ${relativePath}`);\n return null;\n }\n }\n\n // 取前 5 段,之后是说明文字\n const cron = parseExp(cx, tokens.slice(0, 5).join(' '), relativePath, timezone);\n return cron ? { cron, timezone } : null;\n}\n\n/**\n * 从文件内容提取带标记的 cron 表达式,并组合成`JobItem`,一次性提供\n * cron表达式对象、分组信息、文件路径以及解释器信息\n *\n * @param filepath 文件路径,用于日志输出\n * @param content 文件头内容(可以是整文件;第一行正式代码之后的不会用到)\n */\nexport function getJobItem(cx: CronjobContext, filepath: string, content: string): JobItem | null {\n const ext = extname(filepath);\n const allowFn = getAllowFn(ext);\n\n let lines = content.split('\\n').map((line) => line.trim());\n\n if (lines.length === 0) {\n return null;\n }\n\n const shebang = getShebang(lines[0]);\n\n if (shebang) {\n lines.shift();\n }\n\n if (lines.length === 0) {\n return null;\n }\n\n // 第一行放行shebang\n const firstNotAllowedIndex = lines.findIndex((v) => !allowFn(v));\n if (firstNotAllowedIndex !== -1) {\n // 切除到第一行正式代码为止,上面的都可以用来记录@cron\n lines = lines.slice(0, firstNotAllowedIndex);\n }\n\n if (lines.length === 0) {\n return null;\n }\n\n const list: CronGroupItem[] = [];\n // 主日志统一用相对路径(CLAUDE.md 约定)\n const relativePath = relative(cx.dir, filepath);\n\n let inCronBlock = false;\n let group = 0;\n for (const line of lines) {\n const extracted = extractCron(cx, line, inCronBlock, relativePath);\n // 忽略空的\n if (!extracted) {\n continue;\n }\n\n if (extracted === Marker.BEGIN) {\n // 已经在快中,再次碰到begin,则语法错误不予解析\n if (inCronBlock) {\n cx.log.err(`Nested ${Marker.BEGIN} found in file: ${relativePath}`);\n return null;\n }\n group++;\n inCronBlock = true;\n continue;\n }\n\n if (extracted === Marker.END) {\n // 并不在块中,却直接碰到end,语法错误不予解析\n if (!inCronBlock) {\n cx.log.err(`${Marker.END} didn't match ${Marker.BEGIN} in file: ${relativePath}`);\n return null;\n }\n inCronBlock = false;\n continue;\n }\n\n // 时区跟着解析结果走:@cron 与 @cronutc 同时出现时标记不匹配的错误已在 extractCron 里拦下\n list.push({ ...extracted, group: inCronBlock ? group : 0 });\n }\n\n // 语法错误不予解析\n if (inCronBlock) {\n cx.log.err(`Unclosed ${Marker.BEGIN}/${Marker.END} block in file: ${relativePath}`);\n return null;\n }\n\n const interpreter = shebang ?? getDefaultInterpreter(cx.runtime, ext);\n\n return { flatCronGroups: list, interpreter, filepath };\n}\n","import type { CronjobContext } from '../types/config.js';\n\nimport { open, readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\n\n/** 文件头最多读 64KB;比这小的文件由调用方直接整读 */\nexport const MAX_HEADER = 64 * 1024;\n\n/**\n * 只读大文件的前 MAX_HEADER 字节,一次定位读,不循环。\n * - 读出来的内容可能带上一行正式代码或半行,没关系:getJobItem 会在第一行正式代码处切掉\n * - 只有前 64KB 全是注释(说明文件头真的超长)才记 WARN,避免每个大文件每分钟刷一条\n */\nexport async function readHeader(\n cx: CronjobContext,\n filepath: string,\n allowLine: (line: string) => boolean,\n): Promise<string | null> {\n const s = await stat(filepath);\n if (!s.isFile()) {\n cx.log.warn(`Skipped non-regular file: ${path.relative(cx.dir, filepath)}`);\n return null;\n }\n if (s.size < MAX_HEADER) {\n return await readFile(filepath, 'utf8');\n }\n\n const fh = await open(filepath, 'r');\n try {\n const buf = Buffer.alloc(MAX_HEADER);\n const { bytesRead } = await fh.read(buf, 0, MAX_HEADER, 0);\n const text = buf.subarray(0, bytesRead).toString('utf8');\n if (bytesRead === MAX_HEADER && text.split('\\n').every((line) => allowLine(line.trim()))) {\n cx.log.warn(`Header longer than ${MAX_HEADER} bytes, truncated: ${path.relative(cx.dir, filepath)}`);\n }\n return text;\n } finally {\n await fh.close();\n }\n}\n","import type { Job, JobItem } from '../types/global.js';\nimport type { CronjobContext } from '../types/config.js';\n\nimport path from 'node:path';\n\nimport { getJobItem } from './extract.js';\nimport { matches } from '../cron/parse.js';\nimport { getAllowFn } from './allow.js';\nimport { readHeader } from './header.js';\n\nexport type FileContent =\n | {\n filepath: string;\n /** null = 已跳过(非普通文件),readHeader 已经记过 WARN,不算读取失败 */\n content: string | null;\n error: null;\n }\n | {\n filepath: string;\n content: null;\n error: any;\n };\n\nconst CHUNK_SIZE = 100;\n\n/**\n * stat 并读取文件头,一个文件对应一条结果,失败也包成结果、不抛出。\n * - 先 stat:FIFO、设备、目录等非普通文件直接跳过(对 FIFO 做 readFile 会永久阻塞线程池)\n * - 只读文件头:大文件不再整读进内存\n */\nexport async function loadFiles(cx: CronjobContext, filepaths: string[]): Promise<Array<FileContent>> {\n const result: Array<FileContent> = [];\n for (let i = 0; i < filepaths.length; i += CHUNK_SIZE) {\n const promises = filepaths.slice(i, i + CHUNK_SIZE).map(async (filepath): Promise<FileContent> => {\n try {\n const allower = getAllowFn(path.extname(filepath));\n const content = await readHeader(cx, filepath, allower);\n return { filepath, content, error: null };\n } catch (error) {\n return { filepath, content: null, error };\n }\n });\n const r = await Promise.all(promises);\n result.push(...r);\n }\n\n return result;\n}\n\n/**\n * 获取现在应该运行的job\n * - 不会有人写非常多的 cron 表达式,直接遍历即可\n *\n * ! 仅用于同一个filepath\n *\n * @param cx Cronjob 上下文\n * @param item JobItem 对象\n * @param now 当前时间,**秒数、毫秒数为0**\n */\nexport function getMatchedJob(cx: CronjobContext, item: JobItem, now: Date): Job {\n let count = 0;\n const set = new Set<number>();\n for (let i = 0; i < item.flatCronGroups.length; i++) {\n const job = item.flatCronGroups[i];\n if (job.group === 0 && matches(job.cron, now)) {\n count++;\n continue;\n }\n if (!set.has(job.group) && matches(job.cron, now)) {\n count++;\n set.add(job.group);\n }\n }\n return { filepath: item.filepath, interpreter: item.interpreter, count };\n}\n\n/**\n * 判断文件本轮是否该运行\n *\n * @param cx Cronjob 上下文\n * @param files 文件内容数组\n * @param now 当前时间,**秒数、毫秒数为0**\n * @returns 要跑的 cron,要跑多少次;\n */\nexport function getJobs(cx: CronjobContext, files: FileContent[], now: Date): Job[] {\n const jobs: Job[] = [];\n\n for (let i = 0; i < files.length; i++) {\n const f = files[i];\n if (f.error) {\n cx.log.err(`Error loading file ${path.relative(cx.dir, f.filepath)}: ${f.error}`);\n continue;\n }\n if (f.content === null) {\n // 非普通文件:readHeader 已经记过 WARN,这里不再刷 Error\n continue;\n }\n\n const jobItem = getJobItem(cx, f.filepath, f.content);\n if (!jobItem) {\n continue;\n }\n\n // 这里要把shebang算好,matchedjob要运行多少次直接看数字\n const job = getMatchedJob(cx, jobItem, now);\n if (job.count > 0) {\n jobs.push(job);\n }\n }\n\n return jobs;\n}\n","import type { CronjobContext } from './types/config.js';\nimport { createHash } from 'node:crypto';\nimport { mkdirSync, realpathSync, statSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport net from 'node:net';\n\nimport { CMD_NONE } from './context/interpreter.js';\nimport { DIR_MODE } from './consts.js';\n\n/** 持有引用,防止 unref 后的 server 被 GC,导致锁被提前释放 */\nlet _lock: net.Server | null = null;\n\n/**\n * 检查 tsx 是否可用;没有只警告,纯 js/sh 任务仍可运行\n */\nconst orTsx = (cx: CronjobContext) => {\n if (!cx.runtime.hasTsx) {\n cx.log.warn(`'tsx' not found, .ts files will be run by node directly. Not all nodejs versions supports this.`);\n }\n};\n\nconst orPython = (cx: CronjobContext) => {\n if (cx.runtime.pythonCmd !== CMD_NONE) {\n cx.log.info(`python available, .py files will be run by ${cx.runtime.pythonCmd}`);\n } else {\n cx.log.warn('python not available, .py jobs will be ignored');\n }\n};\n\nconst ensureDir = (cx: CronjobContext) => {\n mkdirSync(cx.dir, { recursive: true, mode: DIR_MODE });\n if (cx.dir !== cx.logDir) {\n mkdirSync(cx.logDir, { recursive: true, mode: DIR_MODE });\n }\n};\n\n/**\n * dir / logDir 必须只有 runner 用户能写。\n * - dir 可写 = 能以 runner 的身份执行任意代码;logDir 可写 = 能往任务日志里追加内容\n * - 属主不是当前用户、或 group/other 有写位,都直接报错(不是告警)\n * - root 除外:root 能写任何目录,这条检查对 root 没有意义\n */\nconst checkDirPermissions = (cx: CronjobContext) => {\n if (typeof process.getuid !== 'function' || process.getuid() === 0) {\n return;\n }\n for (const [name, dir] of [\n ['dir', cx.dir],\n ['logDir', cx.logDir],\n ] as const) {\n const { mode, uid } = statSync(dir);\n const writableByOthers = (mode & 0o022) !== 0;\n if (uid !== process.getuid() || writableByOthers) {\n throw new Error(\n `${name} must be owned by the current user and not group/world-writable: ${dir} ` +\n `(owner=${uid}, mode=${(mode & 0o777).toString(8)})`,\n );\n }\n }\n};\n\n/** 写日志时用:任务输出可能含密钥,不让同机其他用户读 */\nexport const LOG_FILE_MODE = 0o640;\n\n/**\n * 锁名用的目录标识:realpath 兜住符号链接(/a/link 与 /b/real 是同一个目录时也能识别),\n * 目录还不存在时退回 resolve 的结果(ensureDir 在拿锁之后才建目录)。\n */\nconst lockKeyOf = (dir: string) => {\n try {\n return realpathSync(dir);\n } catch {\n return resolve(dir);\n }\n};\n\n/**\n * 绑定成功则 resolve(进程活着就一直占着);\n * 已被占用则 reject —— 不 process.exit,由宿主决定怎么退。\n * @returns {Promise<void>}\n */\nconst acquireLock = (cx: CronjobContext) =>\n new Promise<void>((resolve, reject) => {\n /**\n * 锁名跟着任务目录走,同一台机器跑多个项目时不会互相误伤。\n * \\0 前缀 = 抽象 namespace,不落盘;进程退出(含 kill -9)由内核自动释放。\n * exclusive: true —— cluster 模式下 listen 默认交给 primary 代绑并共享句柄,\n * 每个 worker 都会\"成功\",锁就失效了;exclusive 让每个 worker 自己真绑,第二个拿到 EADDRINUSE。\n */\n const LOCK_NAME = '\\0krontab-' + createHash('sha1').update(lockKeyOf(cx.dir)).digest('hex').slice(0, 8);\n const server = net.createServer();\n server.once('error', (e: NodeJS.ErrnoException) => {\n reject(e.code === 'EADDRINUSE' ? new Error('krontab already running') : e);\n });\n server.listen({ path: LOCK_NAME, exclusive: true }, () => {\n server.unref(); // 不阻止进程退出\n _lock = server;\n resolve();\n });\n });\n\nexport const initialize = async (cx: CronjobContext) => {\n // 先拿锁:重复实例不必再做后面的探测\n await acquireLock(cx);\n ensureDir(cx);\n checkDirPermissions(cx);\n orTsx(cx);\n orPython(cx);\n};\n","import type { Job } from './types/global.js';\nimport type { CronjobContext } from './types/config.js';\n\nimport { spawn } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { env } from 'node:process';\n\nimport { CMD_NONE } from './context/interpreter.js';\nimport { LOG_FILE_MODE } from './initialize.js';\n\nexport function run(cx: CronjobContext, { filepath, interpreter }: Job) {\n let output: number | null = null;\n const closeOutput = () => {\n if (output !== null) {\n fs.closeSync(output);\n output = null; // ! 防止反复close\n }\n };\n // 主日志统一用相对路径,绝对路径只用于 spawn\n const relativePath = path.relative(cx.dir, filepath);\n try {\n // 把相对于cron文件夹的路径也带入到日志路径中,这样符合直觉\n const logfile = path.join(cx.logDir, relativePath + '.log');\n\n // 子目录下的脚本,其日志子目录也要存在,否则 shell 重定向失败、命令不会执行\n fs.mkdirSync(path.dirname(logfile), { recursive: true });\n\n // 运行这个文件\n if (interpreter.cmd === CMD_NONE) {\n cx.log.warn(`path=${relativePath} unsupported extension`);\n return;\n }\n\n const cmd = interpreter.cmd;\n const args = interpreter.args.concat(filepath);\n\n output = fs.openSync(logfile, 'a', LOG_FILE_MODE);\n\n const child = spawn(cmd, args, {\n stdio: ['ignore', output, output],\n detached: true,\n env,\n // 子进程 cwd 默认和主程序一样,或者以--cwd=xxx录入\n cwd: cx.jobcwd(filepath),\n });\n\n child.on('error', (e) => {\n closeOutput();\n cx.log.err(`path=${relativePath} pid=${child.pid ?? '-1'}`, e);\n });\n child.on('spawn', () => {\n closeOutput();\n cx.log.spawn(`path=${relativePath} pid=${child.pid ?? '-1'}`);\n });\n child.on('exit', (code, signal) => {\n closeOutput();\n cx.log.exit(`path=${relativePath} pid=${child.pid ?? '-1'} code=${code} signal=${signal}`);\n });\n child.unref();\n } catch (e) {\n closeOutput();\n // spawn 之前的异常(mkdir/openSync/jobcwd 等)也要进主日志,否则无法定位\n cx.log.err(`path=${relativePath} pid=-1`, e);\n }\n}\n","import path from 'node:path';\n\nimport type { CronjobContext } from './types/config.js';\nimport { tryGlobSync } from './utils.js';\nimport { loadFiles } from './syntax/job.js';\nimport { getJobItem } from './syntax/extract.js';\nimport { parseExp } from './cron/parse.js';\n\n/**\n * 罗列所有定时表达式,效果类似 `crontab -l`\n *\n * 输出四列:下次运行时间、表达式、相对路径、解释器命令\n * - 块内的多条表达式会缩进显示,并标出 group\n * - 同一条表达式每次都重新 parse,避免 next() 改动共享对象的内部游标\n */\nexport async function list(cx: CronjobContext) {\n const filepaths = tryGlobSync(cx);\n if (!filepaths) {\n return;\n }\n if (filepaths.length === 0) {\n cx.log.info(`No scripts found in ${cx.dir}`);\n return;\n }\n\n const files = await loadFiles(cx, filepaths);\n\n for (const f of files) {\n const relativePath = path.relative(cx.dir, f.filepath);\n\n if (f.error) {\n cx.log.err(`Error loading file ${relativePath}: ${f.error}`);\n continue;\n }\n if (f.content === null) {\n // 非普通文件:readHeader 已经记过 WARN\n continue;\n }\n\n const item = getJobItem(cx, f.filepath, f.content);\n if (!item) {\n continue;\n }\n\n if (item.flatCronGroups.length === 0) {\n cx.log.warn(`No cron expression: ${relativePath}`);\n continue;\n }\n\n const invocation = [item.interpreter.cmd, ...item.interpreter.args, relativePath].join(' ');\n\n for (const { cron, group, timezone } of item.flatCronGroups) {\n const exp = cron.stringify();\n const next = nextRunText(cx, exp, f.filepath, timezone);\n const prefix = (group > 0 ? ` [${group}] ` : '') + (timezone === 'UTC' ? 'UTC ' : '');\n console.log(`${next.padEnd(24)} ${(prefix + exp).padEnd(18)} ${relativePath.padEnd(32)} ${invocation}`);\n }\n }\n}\n\n/** 表达式在上一次 parse 后可能因 impossible date 抛错,这里只展示、不中断整个列表 */\nfunction nextRunText(cx: CronjobContext, exp: string, filepath: string, timezone: string) {\n const parsed = parseExp(cx, exp, filepath, timezone);\n if (!parsed) {\n return '(invalid)';\n }\n try {\n return cx.timeFormat.format(parsed.next().toDate());\n } catch {\n return '(no next run)';\n }\n}\n","/**\n * # 全局定时任务主理,以每分钟读取来决定是否运行\n * # 1. 只支持:【分 时 日 月 周】 的写法\n * # 2. cron 表达式写在脚本的文件头注释区(第一条正式代码之前的注释),以注释给出\n */\nimport type { UserCronjobConfig } from './types/config.js';\nimport { performance } from 'node:perf_hooks';\n\nimport { createContext } from './context/index.js';\nimport { CronjobState } from './consts.js';\nimport { tryGlobSync } from './utils.js';\nimport { runTask, type TaskController } from './cron/task.js';\nimport { getJobs, loadFiles } from './syntax/job.js';\nimport { run } from './run.js';\nimport { initialize } from './initialize.js';\nimport { list } from './list.js';\n\nexport type { TaskController } from './cron/task.js';\nexport { UserCronjobConfig };\n\n/**\n * 启动定时任务主理,返回控制器\n * - 只支持 5 段 cron:分 时 日 月 周\n * - 同一 dir 只允许一个实例\n */\nexport async function cronjob(config?: Partial<UserCronjobConfig>): Promise<TaskController> {\n const cx = createContext(config);\n cx.log.info(`Config loaded: ${JSON.stringify(cx)}`);\n\n if (process.argv.includes('--list') || process.argv.includes('-l')) {\n // 列出所有任务看一下效果就退出\n await list(cx);\n process.exit(0);\n }\n\n await initialize(cx);\n\n const taskFn = async (now: Date) => {\n // 1、查找CRONJOB_DIR下面的所有符合suffix的文件\n const filepaths = tryGlobSync(cx);\n if (!filepaths) {\n return;\n }\n if (filepaths.length === 0) {\n cx.log.info(`No scripts found.`);\n return;\n }\n\n const performanceNow = performance.now();\n cx.log.debug(`Start`);\n\n const files = await loadFiles(cx, filepaths);\n const jobs = await getJobs(cx, files, now);\n\n // 读文件期间可能被 stop() / pause()(F33):已不在 Running 就不再 spawn 这一轮\n if (cx.jobState === CronjobState.Stopped) {\n return;\n }\n\n for (let i = 0; i < jobs.length; i++) {\n for (let n = 0; n < jobs[i].count; n++) {\n if (cx.jobState === CronjobState.Running) {\n run(cx, jobs[i]);\n }\n }\n }\n\n cx.log.debug(`Finished in ${(performance.now() - performanceNow).toFixed(6)}ms`);\n };\n\n const task = runTask(cx, taskFn);\n\n cx.log.info(`Cronjob start! pid=${process.pid}`);\n\n return task;\n}\n"],"mappings":"A,+zBAuBO,IAAUwD,GAAV,SAAAC,EAAA,CACeA,EAAA,KAAA,QACCA,EAAA,MAAA,UAEAA,EAAA,MAAA,aACMA,EAAA,YAAA,eACRA,EAAA,IAAA,WACMA,EAAA,UAAA,aAGNA,EAAA,IAAA,WACMA,EAAA,UAAA,YAC1B,EAAA,CAAAD,IAAA,CAAA,CAAD,EC9BA,MAAME,EAAUC,GAAgBA,EAAI,SAAS,GAAG,GAAKA,EAAI,SAAS,IAAI,EAUtE,SAAgBC,EAAcD,EAA4B,CACxD,GAAID,EAAOC,CAAG,EACZ,OAAA,EAAO3D,EAAAA,WAAAA,CAAW2D,CAAG,EAAIA,EAAM,KAEjC,IAAK,IAAME,KAAQ5D,EAAAA,IAAI,MAAQ,+BAAA,CAAgC,MAAMC,EAAAA,SAAS,EAC5E,GAAI2D,IAAA,EAAO7D,EAAAA,WAAAA,EAAAA,EAAWG,EAAAA,KAAAA,CAAK0D,EAAKF,CAAG,CAAC,EAClC,OAAOA,EAGX,OAAO,IACT,CAQA,SAAgBG,GAAgB,CAC9B,IAAMC,EAAQ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,EAChC,GAAI,CAACqD,EACH,OAEF,GAAIA,EAAU,SAAW,EAAG,CAC1BrD,EAAG,IAAI,KAAK,mBAAmB,EAC/B,MACF,CAEA,IAAMiG,EAAiBnK,EAAAA,YAAY,IAAI,EACvCkE,EAAG,IAAI,MAAM,OAAO,EAEpB,IAAMgE,EAAQ,MAAMZ,EAAUpD,EAAIqD,CAAS,EACrCY,EAAO,MAAMF,EAAQ/D,EAAIgE,EAAOxD,CAAG,EAGzC,GAAIR,EAAG,WAAA,EAIP,KAAK,IAAIrD,EAAI,EAAGA,EAAIsH,EAAK,OAAQtH,IAC/B,IAAK,IAAI,EAAI,EAAG,EAAIsH,EAAKtH,EAAE,CAAC,MAAO,IAC7BqD,EAAG,WAAA,GACLmF,EAAInF,EAAIiE,EAAKtH,EAAE,EAKrBqD,EAAG,IAAI,MAAM,gBAAgBlE,EAAAA,YAAY,IAAI,EAAImK,EAAA,CAAgB,QAAQ,CAAC,EAAE,GAAG,CAL1D,CAMvB,CAE+B,EAI/B,OAFAjG,EAAG,IAAI,KAAK,sBAAsB,QAAQ,KAAK,EAExCgG,CACT"}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* # 全局定时任务主理,以每分钟读取来决定是否运行
|
|
3
|
+
* # 1. 只支持:【分 时 日 月 周】 的写法
|
|
4
|
+
* # 2. cron 表达式写在脚本的文件头注释区(第一条正式代码之前的注释),以注释给出
|
|
5
|
+
*/
|
|
6
|
+
declare const enum Tag {
|
|
7
|
+
Info = "[INFO]",
|
|
8
|
+
Spawn = "[SPAWN]",
|
|
9
|
+
Error = "[ERROR]",
|
|
10
|
+
Warn = "[WARN]",
|
|
11
|
+
Exit = "[EXIT]",
|
|
12
|
+
Debug = "[DEBUG]"
|
|
13
|
+
}
|
|
14
|
+
interface UserCronjobConfig {
|
|
15
|
+
/**
|
|
16
|
+
* Will scan this directory for cronjob scripts
|
|
17
|
+
*/
|
|
18
|
+
dir: string;
|
|
19
|
+
/**
|
|
20
|
+
* Will put log files there.
|
|
21
|
+
* - Share the same structure as the cronjob scripts directory
|
|
22
|
+
* default value is the same as `this.dir`
|
|
23
|
+
*/
|
|
24
|
+
logDir: string;
|
|
25
|
+
/**
|
|
26
|
+
* Glob expressions to get cronjob scripts.
|
|
27
|
+
* - Will be passed to fs.glob
|
|
28
|
+
*
|
|
29
|
+
* default value is `['**/*.{ts,js,sh}']` (i.e. `**` slash `*.{ts,js,sh}`)
|
|
30
|
+
*/
|
|
31
|
+
include: string[];
|
|
32
|
+
/**
|
|
33
|
+
* Glob expressions to exclude cronjob scripts.
|
|
34
|
+
* - Will be passed to fs.glob as `exclude`
|
|
35
|
+
* - Replaces the default entirely (the two arrays are not merged)
|
|
36
|
+
* - default value drops node_modules, .git, .vscode, .claude, __pycache__,
|
|
37
|
+
* dist, dist-tsc and coverage, each at any depth
|
|
38
|
+
*/
|
|
39
|
+
exclude: string[];
|
|
40
|
+
/**
|
|
41
|
+
* Affects log time and cron parsing.
|
|
42
|
+
*
|
|
43
|
+
* default value is `"Asia/Shanghai"`
|
|
44
|
+
*/
|
|
45
|
+
timezone: string;
|
|
46
|
+
/**
|
|
47
|
+
* The working directory for the running cronjob scripts.
|
|
48
|
+
* - Use function to determine dynamic cwd by the script path.
|
|
49
|
+
*
|
|
50
|
+
* default value is the same as `this.dir`
|
|
51
|
+
*/
|
|
52
|
+
jobcwd: string | ((scriptPath: string) => string);
|
|
53
|
+
/**
|
|
54
|
+
* Function to write logs.
|
|
55
|
+
* @param tag The tag for the log entry.
|
|
56
|
+
* @param args The arguments to log.
|
|
57
|
+
*
|
|
58
|
+
* default value writes `<dtm> <tag> <args>` to console
|
|
59
|
+
*/
|
|
60
|
+
write: (tag: Tag, ...args: any[]) => void;
|
|
61
|
+
}
|
|
62
|
+
interface TaskController {
|
|
63
|
+
/** 停止调度:清掉还没触发的定时器,状态置为 Stopped */
|
|
64
|
+
stop: () => void;
|
|
65
|
+
/** 暂停:定时器继续走,但到点不执行 */
|
|
66
|
+
pause: () => void;
|
|
67
|
+
/** 恢复 */
|
|
68
|
+
resume: () => void;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* 启动定时任务主理,返回控制器
|
|
72
|
+
* - 只支持 5 段 cron:分 时 日 月 周
|
|
73
|
+
* - 同一 dir 只允许一个实例
|
|
74
|
+
*/
|
|
75
|
+
export declare function cronjob(config?: Partial<UserCronjobConfig>): Promise<TaskController>;
|
|
76
|
+
export type { TaskController, UserCronjobConfig };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* # 全局定时任务主理,以每分钟读取来决定是否运行
|
|
3
|
+
* # 1. 只支持:【分 时 日 月 周】 的写法
|
|
4
|
+
* # 2. cron 表达式写在脚本的文件头注释区(第一条正式代码之前的注释),以注释给出
|
|
5
|
+
*/
|
|
6
|
+
import "cron-parser";
|
|
7
|
+
declare const enum Tag {
|
|
8
|
+
Info = "[INFO]",
|
|
9
|
+
Spawn = "[SPAWN]",
|
|
10
|
+
Error = "[ERROR]",
|
|
11
|
+
Warn = "[WARN]",
|
|
12
|
+
Exit = "[EXIT]",
|
|
13
|
+
Debug = "[DEBUG]"
|
|
14
|
+
}
|
|
15
|
+
interface UserCronjobConfig {
|
|
16
|
+
/**
|
|
17
|
+
* Will scan this directory for cronjob scripts
|
|
18
|
+
*/
|
|
19
|
+
dir: string;
|
|
20
|
+
/**
|
|
21
|
+
* Will put log files there.
|
|
22
|
+
* - Share the same structure as the cronjob scripts directory
|
|
23
|
+
* default value is the same as `this.dir`
|
|
24
|
+
*/
|
|
25
|
+
logDir: string;
|
|
26
|
+
/**
|
|
27
|
+
* Glob expressions to get cronjob scripts.
|
|
28
|
+
* - Will be passed to fs.glob
|
|
29
|
+
*
|
|
30
|
+
* default value is `['**/*.{ts,js,sh}']` (i.e. `**` slash `*.{ts,js,sh}`)
|
|
31
|
+
*/
|
|
32
|
+
include: string[];
|
|
33
|
+
/**
|
|
34
|
+
* Glob expressions to exclude cronjob scripts.
|
|
35
|
+
* - Will be passed to fs.glob as `exclude`
|
|
36
|
+
* - Replaces the default entirely (the two arrays are not merged)
|
|
37
|
+
* - default value drops node_modules, .git, .vscode, .claude, __pycache__,
|
|
38
|
+
* dist, dist-tsc and coverage, each at any depth
|
|
39
|
+
*/
|
|
40
|
+
exclude: string[];
|
|
41
|
+
/**
|
|
42
|
+
* Affects log time and cron parsing.
|
|
43
|
+
*
|
|
44
|
+
* default value is `"Asia/Shanghai"`
|
|
45
|
+
*/
|
|
46
|
+
timezone: string;
|
|
47
|
+
/**
|
|
48
|
+
* The working directory for the running cronjob scripts.
|
|
49
|
+
* - Use function to determine dynamic cwd by the script path.
|
|
50
|
+
*
|
|
51
|
+
* default value is the same as `this.dir`
|
|
52
|
+
*/
|
|
53
|
+
jobcwd: string | ((scriptPath: string) => string);
|
|
54
|
+
/**
|
|
55
|
+
* Function to write logs.
|
|
56
|
+
* @param tag The tag for the log entry.
|
|
57
|
+
* @param args The arguments to log.
|
|
58
|
+
*
|
|
59
|
+
* default value writes `<dtm> <tag> <args>` to console
|
|
60
|
+
*/
|
|
61
|
+
write: (tag: Tag, ...args: any[]) => void;
|
|
62
|
+
}
|
|
63
|
+
interface TaskController {
|
|
64
|
+
/** 停止调度:清掉还没触发的定时器,状态置为 Stopped */
|
|
65
|
+
stop: () => void;
|
|
66
|
+
/** 暂停:定时器继续走,但到点不执行 */
|
|
67
|
+
pause: () => void;
|
|
68
|
+
/** 恢复 */
|
|
69
|
+
resume: () => void;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* 启动定时任务主理,返回控制器
|
|
73
|
+
* - 只支持 5 段 cron:分 时 日 月 周
|
|
74
|
+
* - 同一 dir 只允许一个实例
|
|
75
|
+
*/
|
|
76
|
+
export declare function cronjob(config?: Partial<UserCronjobConfig>): Promise<TaskController>;
|
|
77
|
+
export type { TaskController, UserCronjobConfig };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{performance as e}from"node:perf_hooks";import t,{delimiter as n,extname as r,join as i,relative as a,resolve as o}from"node:path";import s,{existsSync as c,mkdirSync as l,realpathSync as u,statSync as d}from"node:fs";import{env as f}from"node:process";import{CronExpressionParser as p}from"cron-parser";import{open as m,readFile as h,stat as g}from"node:fs/promises";import{spawn as _}from"node:child_process";import{createHash as v}from"node:crypto";import y from"node:net";let b;(function(e){e.CRON=`@cron`,e.REGEX=/@cron\b/,e.BEGIN=`@cronbegin`,e.BEGIN_REGEX=/@cronbegin\b/,e.END=`@cronend`,e.END_REGEX=/@cronend\b/,e.UTC=`@cronutc`,e.UTC_REGEX=/@cronutc\b/})(b||={});const x=e=>e.includes(`/`)||e.includes(`\\`);function S(e){if(x(e))return c(e)?e:null;for(let t of(f.PATH||`/usr/local/bin:/usr/bin:/bin`).split(n))if(t&&c(i(t,e)))return e;return null}function C(){let e=S(`tsx`)??S(`ts-node`)??process.execPath,t=e=>({cmd:e,args:[]}),n={".ts":t(e),".mts":t(e),".cts":t(e),".js":t(process.execPath),".mjs":t(process.execPath),".cjs":t(process.execPath),".py":{cmd:S(`python3`)||S(`python`)||`none`,args:[]},".sh":{cmd:S(`bash`)||`sh`,args:[]},none:{cmd:`none`,args:[]}};return{interpreters:n,hasTsx:e!==process.execPath,pythonCmd:n[`.py`].cmd}}function w(e,t){return e.interpreters[t]||e.interpreters.none}function T(e){return{info:(...t)=>e(`[INFO]`,...t),err:(...t)=>e(`[ERROR]`,...t),warn:(...t)=>e(`[WARN]`,...t),spawn:(...t)=>e(`[SPAWN]`,...t),exit:(...t)=>e(`[EXIT]`,...t),debug:(...t)=>e(`[DEBUG]`,...t)}}function E(e){return(t,...n)=>console.log(e.format(/* @__PURE__ */ new Date),t,...n)}const D={include:[`**/*.{ts,js,sh}`],exclude:[`**/node_modules/`,`**/.git/`,`**/.vscode/`,`**/.claude/`,`**/__pycache__/`,`**/dist/`,`**/dist-tsc/`,`**/coverage/`],timezone:`Asia/Shanghai`},O=e=>new Intl.DateTimeFormat(`zh-CN`,{year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,fractionalSecondDigits:3,hour12:!1,timeZone:e});function k(e,t=C()){let{dir:n=process.cwd(),logDir:r=n,jobcwd:i=n,include:a=D.include,exclude:s=D.exclude,timezone:c=D.timezone,write:l}=Object(e);if(typeof n!=`string`)throw TypeError("`dir` must be a string");if(typeof r!=`string`)throw TypeError("`logDir` must be a string");if(typeof i!=`string`&&typeof i!=`function`)throw TypeError("`jobcwd` must be a string or a function");if(l!==void 0&&typeof l!=`function`)throw TypeError("`write` must be a function");if(new Intl.DateTimeFormat(`en-US`,{timeZone:c}),!Array.isArray(a)||a.some(e=>typeof e!=`string`))throw TypeError("`include` must be an array of strings");if(!Array.isArray(s)||s.some(e=>typeof e!=`string`))throw TypeError("`exclude` must be an array of strings");let u=o(n),d=o(r),f=O(c),p=typeof i!=`function`&&i===n?u:i,m=typeof p==`function`?p:()=>p,h=l===void 0?E(f):l;return{dir:u,logDir:d,jobcwd:m,include:a,exclude:s,timezone:c,timeFormat:f,runtime:t,jobState:0,jobTimer:null,write:h,log:T(h)}}const A=e=>{try{return s.globSync(e.include,{cwd:e.dir,exclude:e.exclude}).map(n=>t.resolve(e.dir,n))}catch(t){return e.log.err(`Error while globbing scripts.`,t),null}},j=e=>{let t=new Date(e.getTime()+6e4);return t.setSeconds(0,0),t};function M(e,t){let n=()=>{if(e.jobState===2)return;let r=/* @__PURE__ */ new Date,i=j(r);e.jobTimer=setTimeout(()=>{if(e.jobTimer=null,e.jobState===2)return;
|
|
2
|
+
//! 定时器可能早于边界触发,相当于等了但还没等到呢,再等一会
|
|
3
|
+
if(e.jobState===1||Date.now()<i.getTime()){n();return}let r=/* @__PURE__ */ new Date;r.setSeconds(0,0),n();try{let n=t(r);n&&typeof n.catch==`function`&&n.catch(t=>e.log.err(`Task tick failed:`,t))}catch(t){e.log.err(`Task tick failed:`,t)}},i.getTime()-r.getTime())};return n(),{stop(){e.jobTimer&&=(clearTimeout(e.jobTimer),null),e.jobState=2},pause(){e.jobState===0&&(e.jobState=1)},resume(){e.jobState!==2&&(e.jobState=0,e.jobTimer===null&&n())}}}const N=(e,t,n,r=e.timezone)=>{try{return p.parse(t,{tz:r,hashSeed:n})}catch{return null}};function P(e,t){return e.includesDate(t)}const F=e=>e.startsWith(`//`)||e.startsWith(`/*`)||e.startsWith(`*`)||e.startsWith(`*/`)||e.length===0,I={".ts":F,".mts":F,".cts":F,".js":F,".mjs":F,".cjs":F,".py":e=>/^(#|'''|""")/.test(e)||e.length===0,".sh":e=>e.startsWith(`#`)||e.length===0};function L(e){return I[e]||(()=>!1)}const R=e=>{let[t,...n]=e.split(/\s+/).filter(Boolean);return t?{cmd:t,args:n}:null},z=e=>e.startsWith(`#!`)?R(e.slice(2)):null;function B(e,t,n,r){if(t.search(b.BEGIN_REGEX)!==-1)return b.BEGIN;if(t.search(b.END_REGEX)!==-1)return b.END;let i=t.search(b.REGEX),a=t.search(b.UTC_REGEX);if(i!==-1&&a!==-1)return e.log.err(`Line contains both ${b.CRON} and ${b.UTC}, nothing scheduled: ${r}`),null;let o=e.timezone,s=-1;if(i===-1?a!==-1&&(o=`UTC`,s=a+b.UTC.length):s=i+b.CRON.length,s===-1)return n&&e.log.warn(`@cron should be used to mark cron expressions in cron blocks: ${r}`),null;let c=t.slice(s).split(/\s+/).filter(Boolean);
|
|
4
|
+
//! 阻止cron-parser 把 4 段自动补齐成另一条合法表达式
|
|
5
|
+
if(c.length<5)return e.log.err(`Invalid cron expression: "${c.join(` `)}" in file: ${r}`),null;if(c.length>=6){let t=c.slice(0,6).join(` `);if(N(e,t,r,o))return e.log.err(`6 fields cron is not supported, use 5 fields instead. Found "${t}" in file: ${r}`),null}let l=N(e,c.slice(0,5).join(` `),r,o);return l?{cron:l,timezone:o}:null}function V(e,t,n){let i=r(t),o=L(i),s=n.split(`
|
|
6
|
+
`).map(e=>e.trim());if(s.length===0)return null;let c=z(s[0]);if(c&&s.shift(),s.length===0)return null;let l=s.findIndex(e=>!o(e));if(l!==-1&&(s=s.slice(0,l)),s.length===0)return null;let u=[],d=a(e.dir,t),f=!1,p=0;for(let t of s){let n=B(e,t,f,d);if(n){if(n===b.BEGIN){if(f)return e.log.err(`Nested ${b.BEGIN} found in file: ${d}`),null;p++,f=!0}else if(n===b.END){if(!f)return e.log.err(`${b.END} didn't match ${b.BEGIN} in file: ${d}`),null;f=!1}else u.push({...n,group:f?p:0})}}return f?(e.log.err(`Unclosed ${b.BEGIN}/${b.END} block in file: ${d}`),null):{flatCronGroups:u,interpreter:c??w(e.runtime,i),filepath:t}}const H=65536;async function U(e,n,r){let i=await g(n);if(!i.isFile())return e.log.warn(`Skipped non-regular file: ${t.relative(e.dir,n)}`),null;if(i.size<65536)return await h(n,`utf8`);let a=await m(n,`r`);try{let i=Buffer.alloc(H),{bytesRead:o}=await a.read(i,0,H,0),s=i.subarray(0,o).toString(`utf8`);return o===65536&&s.split(`
|
|
7
|
+
`).every(e=>r(e.trim()))&&e.log.warn(`Header longer than ${H} bytes, truncated: ${t.relative(e.dir,n)}`),s}finally{await a.close()}}async function W(e,n){let r=[];for(let i=0;i<n.length;i+=100){let a=n.slice(i,i+100).map(async n=>{try{return{filepath:n,content:await U(e,n,L(t.extname(n))),error:null}}catch(e){return{filepath:n,content:null,error:e}}}),o=await Promise.all(a);r.push(...o)}return r}function G(e,t,n){let r=0,i=/* @__PURE__ */ new Set;for(let e=0;e<t.flatCronGroups.length;e++){let a=t.flatCronGroups[e];a.group===0&&P(a.cron,n)?r++:!i.has(a.group)&&P(a.cron,n)&&(r++,i.add(a.group))}return{filepath:t.filepath,interpreter:t.interpreter,count:r}}function K(e,n,r){let i=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.error){e.log.err(`Error loading file ${t.relative(e.dir,o.filepath)}: ${o.error}`);continue}if(o.content===null)continue;let s=V(e,o.filepath,o.content);if(!s)continue;let c=G(e,s,r);c.count>0&&i.push(c)}return i}const q=e=>{e.runtime.hasTsx||e.log.warn(`'tsx' not found, .ts files will be run by node directly. Not all nodejs versions supports this.`)},J=e=>{e.runtime.pythonCmd===`none`?e.log.warn(`python not available, .py jobs will be ignored`):e.log.info(`python available, .py files will be run by ${e.runtime.pythonCmd}`)},Y=e=>{l(e.dir,{recursive:!0,mode:493}),e.dir!==e.logDir&&l(e.logDir,{recursive:!0,mode:493})},X=e=>{if(typeof process.getuid==`function`&&process.getuid()!==0)for(let[t,n]of[[`dir`,e.dir],[`logDir`,e.logDir]]){let{mode:e,uid:r}=d(n),i=!!(e&18);if(r!==process.getuid()||i)throw Error(`${t} must be owned by the current user and not group/world-writable: ${n} (owner=${r}, mode=${(e&511).toString(8)})`)}},Z=e=>{try{return u(e)}catch{return o(e)}},Q=e=>new Promise((t,n)=>{let r=`\0krontab-`+v(`sha1`).update(Z(e.dir)).digest(`hex`).slice(0,8),i=y.createServer();i.once(`error`,e=>{n(e.code===`EADDRINUSE`?/* @__PURE__ */ Error(`krontab already running`):e)}),i.listen({path:r,exclusive:!0},()=>{i.unref(),t()})}),$=async e=>{await Q(e),Y(e),X(e),q(e),J(e)};function ee(e,{filepath:n,interpreter:r}){let i=null,a=()=>{i!==null&&(s.closeSync(i),i=null)},o=t.relative(e.dir,n);try{let c=t.join(e.logDir,o+`.log`);if(s.mkdirSync(t.dirname(c),{recursive:!0}),r.cmd===`none`){e.log.warn(`path=${o} unsupported extension`);return}let l=r.cmd,u=r.args.concat(n);i=s.openSync(c,`a`,416);let d=_(l,u,{stdio:[`ignore`,i,i],detached:!0,env:f,cwd:e.jobcwd(n)});d.on(`error`,t=>{a(),e.log.err(`path=${o} pid=${d.pid??`-1`}`,t)}),d.on(`spawn`,()=>{a(),e.log.spawn(`path=${o} pid=${d.pid??`-1`}`)}),d.on(`exit`,(t,n)=>{a(),e.log.exit(`path=${o} pid=${d.pid??`-1`} code=${t} signal=${n}`)}),d.unref()}catch(t){a(),e.log.err(`path=${o} pid=-1`,t)}}async function te(e){let n=A(e);if(!n)return;if(n.length===0){e.log.info(`No scripts found in ${e.dir}`);return}let r=await W(e,n);for(let n of r){let r=t.relative(e.dir,n.filepath);if(n.error){e.log.err(`Error loading file ${r}: ${n.error}`);continue}if(n.content===null)continue;let i=V(e,n.filepath,n.content);if(!i)continue;if(i.flatCronGroups.length===0){e.log.warn(`No cron expression: ${r}`);continue}let a=[i.interpreter.cmd,...i.interpreter.args,r].join(` `);for(let{cron:t,group:o,timezone:s}of i.flatCronGroups){let i=t.stringify(),c=ne(e,i,n.filepath,s),l=(o>0?` [${o}] `:``)+(s===`UTC`?`UTC `:``);console.log(`${c.padEnd(24)} ${(l+i).padEnd(18)} ${r.padEnd(32)} ${a}`)}}}function ne(e,t,n,r){let i=N(e,t,n,r);if(!i)return`(invalid)`;try{return e.timeFormat.format(i.next().toDate())}catch{return`(no next run)`}}async function re(t){let n=k(t);n.log.info(`Config loaded: ${JSON.stringify(n)}`),(process.argv.includes(`--list`)||process.argv.includes(`-l`))&&(await te(n),process.exit(0)),await $(n);let r=M(n,async t=>{let r=A(n);if(!r)return;if(r.length===0){n.log.info(`No scripts found.`);return}let i=e.now();n.log.debug(`Start`);let a=await W(n,r),o=await K(n,a,t);if(n.jobState!==2){for(let e=0;e<o.length;e++)for(let t=0;t<o[e].count;t++)n.jobState===0&&ee(n,o[e]);n.log.debug(`Finished in ${(e.now()-i).toFixed(6)}ms`)}});return n.log.info(`Cronjob start! pid=${process.pid}`),r}export{re as cronjob};
|
|
8
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["performance","path","delimiter","extname","join","relative","resolve","fs","existsSync","mkdirSync","realpathSync","statSync","env","CronExpressionParser","open","readFile","stat","spawn","createHash","net","Marker","_Marker","isPath","cmd","detectCommand","dir","detectRuntime","tsCmd","jsLike","interpreters","getDefaultInterpreter","runtime","ext","createLogger","write","args","defaultWrite","formatter","tag","DEFAULTS","createFormatter","timezone","createContext","rawConfig","logDir","jobcwd","include","exclude","pattern","absDir","absLogDir","timeFormat","defaultJobcwd","jobcwdFn","writer","tryGlobSync","cx","v","e","nextMinuteBoundary","from","next","runTask","fn","schedule","now","nextMinute","noSecondDate","ret","parseExp","exp","filepath","matches","expression","d","jstsAllow","line","allows","getAllowFn","parse","text","getShebang","extractCron","trimmedLine","inBlock","relativePath","index","utcIndex","expStart","tokens","sixExpStr","cron","getJobItem","content","allowFn","lines","shebang","firstNotAllowedIndex","list","inCronBlock","group","extracted","MAX_HEADER","readHeader","allowLine","s","fh","buf","bytesRead","loadFiles","filepaths","result","promises","error","r","getMatchedJob","item","count","set","i","job","getJobs","files","jobs","f","jobItem","orTsx","orPython","ensureDir","checkDirPermissions","name","mode","uid","writableByOthers","lockKeyOf","acquireLock","reject","LOCK_NAME","server","initialize","run","interpreter","output","closeOutput","logfile","child","code","signal","invocation","nextRunText","prefix","parsed","cronjob","config","task","performanceNow","n"],"sources":["../src/consts.ts","../src/context/interpreter.ts","../src/context/logger.ts","../src/context/index.ts","../src/utils.ts","../src/cron/task.ts","../src/cron/parse.ts","../src/syntax/allow.ts","../src/syntax/shebang.ts","../src/syntax/extract.ts","../src/syntax/header.ts","../src/syntax/job.ts","../src/initialize.ts","../src/run.ts","../src/list.ts","../src/index.ts"],"sourcesContent":["export const enum Tag {\n Info = '[INFO]',\n Spawn = '[SPAWN]',\n Error = '[ERROR]',\n Warn = '[WARN]',\n Exit = '[EXIT]',\n Debug = '[DEBUG]',\n}\n\n/**\n * runner 自己建的目录统一按 0755 创建。\n * - 不能沿用 umask:Debian/Ubuntu 的 USERGROUPS_ENAB 默认 umask 002,mkdir 会建出 775,\n * 紧接着被 checkDirPermissions 拒绝,第一次部署就起不来(F44)\n * - 0755 本身不带 group/other 写位,任何 umask 下都只会更收紧,不会更宽松\n */\nexport const DIR_MODE = 0o755;\n\nexport const enum CronjobState {\n Running,\n Paused,\n Stopped,\n}\n\nexport namespace Marker {\n export const CRON = '@cron' as const;\n export const REGEX = /@cron\\b/;\n\n export const BEGIN = '@cronbegin' as const;\n export const BEGIN_REGEX = /@cronbegin\\b/;\n export const END = '@cronend' as const;\n export const END_REGEX = /@cronend\\b/;\n\n /** 行内标记:`@cronutc <5 段>`,只让这一条按 UTC 解析 */\n export const UTC = '@cronutc' as const;\n export const UTC_REGEX = /@cronutc\\b/;\n}\n\nexport type CronBlockMaker = typeof Marker.BEGIN | typeof Marker.END;\n","import type { Interpreter } from '../types/global.js';\nimport { existsSync } from 'node:fs';\nimport { delimiter, join } from 'node:path';\nimport { env } from 'node:process';\n\nconst isPath = (cmd: string) => cmd.includes('/') || cmd.includes('\\\\');\n\n/**\n * 检测系统中可用的运行时命令。\n * - 只查 PATH、不执行命令:`tsx --version` 实测约 740ms,而探测在 cronjob() 的启动路径上,\n * 每个 cx 都要付一次太贵。代价是\"存在但跑不起来\"的命令会被当成可用,启动时不会发现。\n * - 含路径分隔符的命令直接看文件是否存在,不查 PATH\n * - PATH 为空时(某些 pm2 配置)回退到常见系统目录\n * @returns 可用的命令名,都不可用则返回 null\n */\nexport function detectCommand(cmd: string): string | null {\n if (isPath(cmd)) {\n return existsSync(cmd) ? cmd : null;\n }\n for (const dir of (env.PATH || '/usr/local/bin:/usr/bin:/bin').split(delimiter)) {\n if (dir && existsSync(join(dir, cmd))) {\n return cmd;\n }\n }\n return null;\n}\n\n/** 标记\"没有可用解释器\"的占位命令,run() 见到它只记 WARN 不 spawn */\nexport const CMD_NONE = 'none';\n\n/**\n * 探测所有运行时,返回解释器映射表。\n */\nexport function detectRuntime() {\n const tsCmd = detectCommand('tsx') ?? detectCommand('ts-node') ?? process.execPath;\n const jsLike = (cmd: string): Interpreter => ({ cmd, args: [] });\n\n const interpreters: Record<string, Interpreter> = {\n '.ts': jsLike(tsCmd),\n '.mts': jsLike(tsCmd),\n '.cts': jsLike(tsCmd),\n '.js': jsLike(process.execPath),\n '.mjs': jsLike(process.execPath),\n '.cjs': jsLike(process.execPath),\n '.py': {\n cmd: detectCommand('python3') || detectCommand('python') || CMD_NONE,\n args: [],\n },\n '.sh': {\n cmd: detectCommand('bash') || 'sh',\n args: [],\n },\n none: {\n cmd: CMD_NONE,\n args: [],\n },\n };\n\n return {\n interpreters,\n hasTsx: tsCmd !== process.execPath,\n pythonCmd: interpreters['.py'].cmd,\n };\n}\n\nexport type Runtime = ReturnType<typeof detectRuntime>;\n\n/** 取扩展名对应的解释器;没有映射的(或映射成 none)交给 run() 记 WARN */\nexport function getDefaultInterpreter(runtime: Runtime, ext: string): Interpreter {\n return runtime.interpreters[ext] || runtime.interpreters.none;\n}\n","import type { CronjobLogger } from '../types/global.js';\nimport type { UserCronjobConfig } from '../types/config.js';\nimport { Tag } from '../consts.js';\n\n/**\n * 把 cx.write 包装成带 tag 的方法。\n * - write 是唯一的输出出口,消费者可以整条替换(默认写 stdout)\n */\nexport function createLogger(write: UserCronjobConfig['write']): CronjobLogger {\n return {\n info: (...args: any[]) => write(Tag.Info, ...args),\n err: (...args: any[]) => write(Tag.Error, ...args),\n warn: (...args: any[]) => write(Tag.Warn, ...args),\n spawn: (...args: any[]) => write(Tag.Spawn, ...args),\n exit: (...args: any[]) => write(Tag.Exit, ...args),\n debug: (...args: any[]) => write(Tag.Debug, ...args),\n };\n}\n\n/** 默认输出:`<dtm> <TAG> <内容>`,dtm 用 cx.timezone */\nexport function defaultWrite(formatter: Intl.DateTimeFormat): UserCronjobConfig['write'] {\n return (tag: Tag, ...args: any[]) => console.log(formatter.format(new Date()), tag, ...args);\n}\n","import type { CronjobContext, UserCronjobConfig } from '../types/config.js';\nimport type { Runtime } from './interpreter.js';\nimport { resolve } from 'node:path';\n\nimport { CronjobState } from '../consts.js';\nimport { detectRuntime } from './interpreter.js';\nimport { createLogger, defaultWrite } from './logger.js';\n\n/** 默认值:只改一处,测试与 createContext 都从这里断言 */\nexport const DEFAULTS = {\n include: ['**/*.{ts,js,sh}'],\n exclude: [\n '**/node_modules/',\n '**/.git/',\n '**/.vscode/',\n '**/.claude/',\n '**/__pycache__/',\n '**/dist/',\n '**/dist-tsc/',\n '**/coverage/',\n ],\n timezone: 'Asia/Shanghai',\n};\n\nconst createFormatter = (timezone: string) =>\n new Intl.DateTimeFormat('zh-CN', {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n fractionalSecondDigits: 3,\n hour12: false,\n timeZone: timezone,\n });\n\n/**\n * 创建上下文:配置校验 + 默认值 + 格式化器 + logger + 运行时映射,一次给齐。\n * - `runtime` 由调用方传入时直接用(便于测试注入);不传就现场探测一次\n * - 探测只查 PATH(见 interpreter.ts),不执行外部命令\n */\nexport function createContext(rawConfig?: Partial<UserCronjobConfig>, runtime: Runtime = detectRuntime()): CronjobContext {\n const {\n dir = process.cwd(),\n logDir = dir,\n jobcwd = dir,\n include = DEFAULTS.include,\n exclude = DEFAULTS.exclude,\n timezone = DEFAULTS.timezone,\n write,\n } = Object(rawConfig) as UserCronjobConfig;\n\n if (typeof dir !== 'string') {\n throw new TypeError('`dir` must be a string');\n }\n\n if (typeof logDir !== 'string') {\n throw new TypeError('`logDir` must be a string');\n }\n\n if (typeof jobcwd !== 'string' && typeof jobcwd !== 'function') {\n throw new TypeError('`jobcwd` must be a string or a function');\n }\n\n if (write !== undefined && typeof write !== 'function') {\n throw new TypeError('`write` must be a function');\n }\n\n // Validate timezone by attempting to create a DateTimeFormat with it\n new Intl.DateTimeFormat('en-US', { timeZone: timezone });\n\n if (!Array.isArray(include) || include.some((pattern) => typeof pattern !== 'string')) {\n throw new TypeError('`include` must be an array of strings');\n }\n if (!Array.isArray(exclude) || exclude.some((pattern) => typeof pattern !== 'string')) {\n throw new TypeError('`exclude` must be an array of strings');\n }\n\n // 统一成绝对路径:单例锁的 key、日志相对路径、glob 的 cwd 都依赖它。\n // 否则 './g'、'/abs/g'、'/abs/g/' 会被当成三个不同的任务目录。\n const absDir = resolve(dir);\n const absLogDir = resolve(logDir);\n\n const timeFormat = createFormatter(timezone);\n\n // jobcwd 是字符串时包装成函数;显式传入的(含默认的 dir)不额外改动\n const defaultJobcwd = typeof jobcwd !== 'function' && jobcwd === dir ? absDir : jobcwd;\n const jobcwdFn = typeof defaultJobcwd === 'function' ? defaultJobcwd : () => defaultJobcwd;\n\n const writer = write === undefined ? defaultWrite(timeFormat) : write;\n\n return {\n dir: absDir,\n logDir: absLogDir,\n jobcwd: jobcwdFn,\n include,\n exclude,\n timezone,\n timeFormat,\n runtime,\n jobState: CronjobState.Running,\n jobTimer: null,\n write: writer,\n log: createLogger(writer),\n };\n}\n","import type { CronjobContext } from './types/config.js';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * 返回要处理的文件的绝对路径\n */\nexport const tryGlobSync = (cx: CronjobContext) => {\n try {\n return fs.globSync(cx.include, { cwd: cx.dir, exclude: cx.exclude }).map((v) => path.resolve(cx.dir, v));\n } catch (e) {\n cx.log.err(`Error while globbing scripts.`, e);\n return null;\n }\n};\n\n/**\n * 用来解决超时问题\n * - 不一定用得上\n */\nexport function nolater<T extends Promise<any>>(cx: CronjobContext, promise: T, ms: number = 2000): T {\n const timeout = new Promise<never>((_, reject) => {\n const id = setTimeout(() => {\n clearTimeout(id);\n reject(new Error(`Promise did not resolve within ${ms}ms`));\n }, ms);\n });\n return Promise.race([promise, timeout]) as T;\n}\n","import type { CronjobContext } from '../types/config.js';\nimport { CronjobState } from '../consts.js';\n\nexport interface TaskController {\n /** 停止调度:清掉还没触发的定时器,状态置为 Stopped */\n stop: () => void;\n /** 暂停:定时器继续走,但到点不执行 */\n pause: () => void;\n /** 恢复 */\n resume: () => void;\n}\n\n/** 下一分钟边界(本地毫秒截断到分钟) */\nconst nextMinuteBoundary = (from: Date) => {\n const next = new Date(from.getTime() + 60000);\n next.setSeconds(0, 0);\n return next;\n};\n\n/**\n * 每分钟执行一次 fn,返回控制对象\n * - 状态全部放在 cx.jobState / cx.jobTimer 里,本函数不持有模块级状态\n * - 每次调度都重新读 cx.jobState,因此 stop/resume 在任意时刻都生效\n */\nexport function runTask(cx: CronjobContext, fn: (now: Date) => void | Promise<void>): TaskController {\n const schedule = () => {\n // 只有 Stopped 才停链;Paused 也要继续排,否则进程会在下一个边界自行退出\n if (cx.jobState === CronjobState.Stopped) {\n return;\n }\n\n const now = new Date();\n const nextMinute = nextMinuteBoundary(now);\n\n cx.jobTimer = setTimeout(() => {\n // 定时器已经触发,句柄作废;stop 时靠它判断是否还有待触发的定时器\n cx.jobTimer = null;\n\n // 到点时状态可能已经变了(stop)\n if (cx.jobState === CronjobState.Stopped) {\n return;\n }\n\n // 暂停期间定时器照常走,只是不执行;否则事件循环会空掉,进程在下一个分钟边界自行退出\n if (cx.jobState === CronjobState.Paused) {\n schedule();\n return;\n }\n\n //! 定时器可能早于边界触发,相当于等了但还没等到呢,再等一会\n if (Date.now() < nextMinute.getTime()) {\n schedule();\n return;\n }\n\n const noSecondDate = new Date();\n noSecondDate.setSeconds(0, 0);\n\n // 先排下一轮:fn 抛错或异步 reject 都不能打断调度链(否则整条链就断了)\n schedule();\n\n try {\n const ret = fn(noSecondDate);\n // 只用一条 Error 记录,不重试、不告警,等下一分钟即可\n if (ret && typeof ret.catch === 'function') {\n ret.catch((e) => cx.log.err(`Task tick failed:`, e));\n }\n } catch (e) {\n cx.log.err(`Task tick failed:`, e);\n }\n }, nextMinute.getTime() - now.getTime());\n };\n\n schedule();\n\n return {\n stop() {\n if (cx.jobTimer) {\n clearTimeout(cx.jobTimer);\n cx.jobTimer = null;\n }\n cx.jobState = CronjobState.Stopped;\n },\n pause() {\n if (cx.jobState === CronjobState.Running) {\n cx.jobState = CronjobState.Paused;\n }\n },\n resume() {\n if (cx.jobState === CronjobState.Stopped) {\n return;\n }\n cx.jobState = CronjobState.Running;\n // 暂停期间定时器没有停,所以这里只需要恢复状态即可;\n // 但如果定时器已经被外部清掉(jobTimer === null),重新排一次\n if (cx.jobTimer === null) {\n schedule();\n }\n },\n };\n}\n","import { type CronExpression, CronExpressionParser } from 'cron-parser';\nimport type { CronjobContext } from '../types/config.js';\n\n/**\n * 非得要try很奇怪,但这是官方推荐的方式\n *\n * @param timezone cron 语义使用的时区;默认是 cx.timezone,`@cronutc` 之后传 'UTC'\n */\nexport const parseExp = (\n cx: CronjobContext,\n exp: string,\n filepath: string,\n timezone: string = cx.timezone,\n): CronExpression | null => {\n try {\n return CronExpressionParser.parse(exp, { tz: timezone, hashSeed: filepath });\n } catch {\n return null;\n }\n};\n\n/**\n * 判断给定日期是否匹配 cron 表达式\n * @param expression cron 表达式\n * @param d 待匹配的日期\n */\nexport function matches(expression: CronExpression, d: Date) {\n // & 已经在task里面完成了这一步:d.setSeconds(0, 0);\n return expression.includesDate(d);\n}\n","/**\n * ! 多行注释以`*`开头是实时标准和社区、行业规范\n */\nconst jstsAllow = (line) =>\n // 单行注释\n line.startsWith('//') ||\n // 多行注释\n line.startsWith('/*') ||\n // 多行注释的第二行\n line.startsWith('*') ||\n // 多行注释的最后一行\n line.startsWith('*/') ||\n // 什么都没有,也可能是多行注释\n line.length === 0;\n\nconst allows = {\n '.ts': jstsAllow,\n '.mts': jstsAllow,\n '.cts': jstsAllow,\n '.js': jstsAllow,\n '.mjs': jstsAllow,\n '.cjs': jstsAllow,\n '.py': (line: string) => /^(#|'''|\"\"\")/.test(line) || line.length === 0,\n '.sh': (line: string) => line.startsWith('#') || line.length === 0,\n};\n\nexport function getAllowFn(ext: string): (line: string) => boolean {\n return allows[ext] || (() => false);\n}\n","import type { Interpreter } from '../types/global.js';\n\nconst parse = (text: string): Interpreter | null => {\n const [cmd, ...args] = text.split(/\\s+/).filter(Boolean);\n return cmd ? { cmd, args } : null;\n};\n\n/**\n * 获取解释器,同时也可用于判定是否存在 shebang\n * - 如果有人只是在第一行写了\"#!\",后面没写任何东西,这里也会返回`null`\n */\nexport const getShebang = (line: string) => (line.startsWith('#!') ? parse(line.slice(2)) : null);\n","import type { CronExpression } from 'cron-parser';\nimport type { CronGroupItem, JobItem } from '../types/global.js';\nimport type { CronjobContext } from '../types/config.js';\n\nimport { extname, relative } from 'node:path';\nimport { type CronBlockMaker, Marker } from '../consts.js';\nimport { parseExp } from '../cron/parse.js';\nimport { getDefaultInterpreter } from '../context/interpreter.js';\nimport { getAllowFn } from './allow.js';\nimport { getShebang } from './shebang.js';\n\n/**\n * 一行解析出来的调度:表达式 + 它实际使用的时区。\n * 时区只在这里决定一次,调用方不要再对整行做第二次标记搜索(F45)。\n */\nexport interface ExtractedCron {\n cron: CronExpression;\n timezone: string;\n}\n\n/**\n * 从一行文本中提取带标记的 cron 表达式\n * - 只接受5位表达式,不支持秒级\n * - `@cronutc <5 段>` 是行内指令:这一条按 UTC 解析,不影响其它行\n *\n * @param trimmedLine 已经去掉前导空格的行文本\n * @param inBlock 是否在 @cronbegin 和 @cronend 块中\n * @param relativePath 相对路径,用于日志输出\n */\nexport function extractCron(\n cx: CronjobContext,\n trimmedLine: string,\n inBlock: boolean,\n relativePath: string,\n): ExtractedCron | CronBlockMaker | null {\n if (trimmedLine.search(Marker.BEGIN_REGEX) !== -1) {\n return Marker.BEGIN;\n }\n if (trimmedLine.search(Marker.END_REGEX) !== -1) {\n return Marker.END;\n }\n\n // @cron的index\n const index = trimmedLine.search(Marker.REGEX);\n // @cronutc的index\n const utcIndex = trimmedLine.search(Marker.UTC_REGEX);\n\n // 同一行两个标记无法判断该按哪个时区跑;宁可拒绝并记 Error,也不猜\n if (index !== -1 && utcIndex !== -1) {\n cx.log.err(`Line contains both ${Marker.CRON} and ${Marker.UTC}, nothing scheduled: ${relativePath}`);\n return null;\n }\n\n let timezone = cx.timezone;\n let expStart = -1;\n\n // 一般都是这个,所以这个排前面,分支预测更好\n if (index !== -1) {\n expStart = index + Marker.CRON.length;\n } else if (utcIndex !== -1) {\n timezone = 'UTC';\n expStart = utcIndex + Marker.UTC.length;\n }\n\n if (expStart === -1) {\n if (inBlock) {\n cx.log.warn(`@cron should be used to mark cron expressions in cron blocks: ${relativePath}`);\n }\n return null;\n }\n\n // 直接切片,从标记后面开始获取字符\n const tokens = trimmedLine.slice(expStart).split(/\\s+/).filter(Boolean);\n\n //! 阻止cron-parser 把 4 段自动补齐成另一条合法表达式\n if (tokens.length < 5) {\n cx.log.err(`Invalid cron expression: \"${tokens.join(' ')}\" in file: ${relativePath}`);\n return null;\n }\n\n // 前 6 段能解析说明写的是秒级定时,本项目只支持 5 段,整行不调度\n if (tokens.length >= 6) {\n const sixExpStr = tokens.slice(0, 6).join(' ');\n if (parseExp(cx, sixExpStr, relativePath, timezone)) {\n cx.log.err(`6 fields cron is not supported, use 5 fields instead. Found \"${sixExpStr}\" in file: ${relativePath}`);\n return null;\n }\n }\n\n // 取前 5 段,之后是说明文字\n const cron = parseExp(cx, tokens.slice(0, 5).join(' '), relativePath, timezone);\n return cron ? { cron, timezone } : null;\n}\n\n/**\n * 从文件内容提取带标记的 cron 表达式,并组合成`JobItem`,一次性提供\n * cron表达式对象、分组信息、文件路径以及解释器信息\n *\n * @param filepath 文件路径,用于日志输出\n * @param content 文件头内容(可以是整文件;第一行正式代码之后的不会用到)\n */\nexport function getJobItem(cx: CronjobContext, filepath: string, content: string): JobItem | null {\n const ext = extname(filepath);\n const allowFn = getAllowFn(ext);\n\n let lines = content.split('\\n').map((line) => line.trim());\n\n if (lines.length === 0) {\n return null;\n }\n\n const shebang = getShebang(lines[0]);\n\n if (shebang) {\n lines.shift();\n }\n\n if (lines.length === 0) {\n return null;\n }\n\n // 第一行放行shebang\n const firstNotAllowedIndex = lines.findIndex((v) => !allowFn(v));\n if (firstNotAllowedIndex !== -1) {\n // 切除到第一行正式代码为止,上面的都可以用来记录@cron\n lines = lines.slice(0, firstNotAllowedIndex);\n }\n\n if (lines.length === 0) {\n return null;\n }\n\n const list: CronGroupItem[] = [];\n // 主日志统一用相对路径(CLAUDE.md 约定)\n const relativePath = relative(cx.dir, filepath);\n\n let inCronBlock = false;\n let group = 0;\n for (const line of lines) {\n const extracted = extractCron(cx, line, inCronBlock, relativePath);\n // 忽略空的\n if (!extracted) {\n continue;\n }\n\n if (extracted === Marker.BEGIN) {\n // 已经在快中,再次碰到begin,则语法错误不予解析\n if (inCronBlock) {\n cx.log.err(`Nested ${Marker.BEGIN} found in file: ${relativePath}`);\n return null;\n }\n group++;\n inCronBlock = true;\n continue;\n }\n\n if (extracted === Marker.END) {\n // 并不在块中,却直接碰到end,语法错误不予解析\n if (!inCronBlock) {\n cx.log.err(`${Marker.END} didn't match ${Marker.BEGIN} in file: ${relativePath}`);\n return null;\n }\n inCronBlock = false;\n continue;\n }\n\n // 时区跟着解析结果走:@cron 与 @cronutc 同时出现时标记不匹配的错误已在 extractCron 里拦下\n list.push({ ...extracted, group: inCronBlock ? group : 0 });\n }\n\n // 语法错误不予解析\n if (inCronBlock) {\n cx.log.err(`Unclosed ${Marker.BEGIN}/${Marker.END} block in file: ${relativePath}`);\n return null;\n }\n\n const interpreter = shebang ?? getDefaultInterpreter(cx.runtime, ext);\n\n return { flatCronGroups: list, interpreter, filepath };\n}\n","import type { CronjobContext } from '../types/config.js';\n\nimport { open, readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\n\n/** 文件头最多读 64KB;比这小的文件由调用方直接整读 */\nexport const MAX_HEADER = 64 * 1024;\n\n/**\n * 只读大文件的前 MAX_HEADER 字节,一次定位读,不循环。\n * - 读出来的内容可能带上一行正式代码或半行,没关系:getJobItem 会在第一行正式代码处切掉\n * - 只有前 64KB 全是注释(说明文件头真的超长)才记 WARN,避免每个大文件每分钟刷一条\n */\nexport async function readHeader(\n cx: CronjobContext,\n filepath: string,\n allowLine: (line: string) => boolean,\n): Promise<string | null> {\n const s = await stat(filepath);\n if (!s.isFile()) {\n cx.log.warn(`Skipped non-regular file: ${path.relative(cx.dir, filepath)}`);\n return null;\n }\n if (s.size < MAX_HEADER) {\n return await readFile(filepath, 'utf8');\n }\n\n const fh = await open(filepath, 'r');\n try {\n const buf = Buffer.alloc(MAX_HEADER);\n const { bytesRead } = await fh.read(buf, 0, MAX_HEADER, 0);\n const text = buf.subarray(0, bytesRead).toString('utf8');\n if (bytesRead === MAX_HEADER && text.split('\\n').every((line) => allowLine(line.trim()))) {\n cx.log.warn(`Header longer than ${MAX_HEADER} bytes, truncated: ${path.relative(cx.dir, filepath)}`);\n }\n return text;\n } finally {\n await fh.close();\n }\n}\n","import type { Job, JobItem } from '../types/global.js';\nimport type { CronjobContext } from '../types/config.js';\n\nimport path from 'node:path';\n\nimport { getJobItem } from './extract.js';\nimport { matches } from '../cron/parse.js';\nimport { getAllowFn } from './allow.js';\nimport { readHeader } from './header.js';\n\nexport type FileContent =\n | {\n filepath: string;\n /** null = 已跳过(非普通文件),readHeader 已经记过 WARN,不算读取失败 */\n content: string | null;\n error: null;\n }\n | {\n filepath: string;\n content: null;\n error: any;\n };\n\nconst CHUNK_SIZE = 100;\n\n/**\n * stat 并读取文件头,一个文件对应一条结果,失败也包成结果、不抛出。\n * - 先 stat:FIFO、设备、目录等非普通文件直接跳过(对 FIFO 做 readFile 会永久阻塞线程池)\n * - 只读文件头:大文件不再整读进内存\n */\nexport async function loadFiles(cx: CronjobContext, filepaths: string[]): Promise<Array<FileContent>> {\n const result: Array<FileContent> = [];\n for (let i = 0; i < filepaths.length; i += CHUNK_SIZE) {\n const promises = filepaths.slice(i, i + CHUNK_SIZE).map(async (filepath): Promise<FileContent> => {\n try {\n const allower = getAllowFn(path.extname(filepath));\n const content = await readHeader(cx, filepath, allower);\n return { filepath, content, error: null };\n } catch (error) {\n return { filepath, content: null, error };\n }\n });\n const r = await Promise.all(promises);\n result.push(...r);\n }\n\n return result;\n}\n\n/**\n * 获取现在应该运行的job\n * - 不会有人写非常多的 cron 表达式,直接遍历即可\n *\n * ! 仅用于同一个filepath\n *\n * @param cx Cronjob 上下文\n * @param item JobItem 对象\n * @param now 当前时间,**秒数、毫秒数为0**\n */\nexport function getMatchedJob(cx: CronjobContext, item: JobItem, now: Date): Job {\n let count = 0;\n const set = new Set<number>();\n for (let i = 0; i < item.flatCronGroups.length; i++) {\n const job = item.flatCronGroups[i];\n if (job.group === 0 && matches(job.cron, now)) {\n count++;\n continue;\n }\n if (!set.has(job.group) && matches(job.cron, now)) {\n count++;\n set.add(job.group);\n }\n }\n return { filepath: item.filepath, interpreter: item.interpreter, count };\n}\n\n/**\n * 判断文件本轮是否该运行\n *\n * @param cx Cronjob 上下文\n * @param files 文件内容数组\n * @param now 当前时间,**秒数、毫秒数为0**\n * @returns 要跑的 cron,要跑多少次;\n */\nexport function getJobs(cx: CronjobContext, files: FileContent[], now: Date): Job[] {\n const jobs: Job[] = [];\n\n for (let i = 0; i < files.length; i++) {\n const f = files[i];\n if (f.error) {\n cx.log.err(`Error loading file ${path.relative(cx.dir, f.filepath)}: ${f.error}`);\n continue;\n }\n if (f.content === null) {\n // 非普通文件:readHeader 已经记过 WARN,这里不再刷 Error\n continue;\n }\n\n const jobItem = getJobItem(cx, f.filepath, f.content);\n if (!jobItem) {\n continue;\n }\n\n // 这里要把shebang算好,matchedjob要运行多少次直接看数字\n const job = getMatchedJob(cx, jobItem, now);\n if (job.count > 0) {\n jobs.push(job);\n }\n }\n\n return jobs;\n}\n","import type { CronjobContext } from './types/config.js';\nimport { createHash } from 'node:crypto';\nimport { mkdirSync, realpathSync, statSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport net from 'node:net';\n\nimport { CMD_NONE } from './context/interpreter.js';\nimport { DIR_MODE } from './consts.js';\n\n/** 持有引用,防止 unref 后的 server 被 GC,导致锁被提前释放 */\nlet _lock: net.Server | null = null;\n\n/**\n * 检查 tsx 是否可用;没有只警告,纯 js/sh 任务仍可运行\n */\nconst orTsx = (cx: CronjobContext) => {\n if (!cx.runtime.hasTsx) {\n cx.log.warn(`'tsx' not found, .ts files will be run by node directly. Not all nodejs versions supports this.`);\n }\n};\n\nconst orPython = (cx: CronjobContext) => {\n if (cx.runtime.pythonCmd !== CMD_NONE) {\n cx.log.info(`python available, .py files will be run by ${cx.runtime.pythonCmd}`);\n } else {\n cx.log.warn('python not available, .py jobs will be ignored');\n }\n};\n\nconst ensureDir = (cx: CronjobContext) => {\n mkdirSync(cx.dir, { recursive: true, mode: DIR_MODE });\n if (cx.dir !== cx.logDir) {\n mkdirSync(cx.logDir, { recursive: true, mode: DIR_MODE });\n }\n};\n\n/**\n * dir / logDir 必须只有 runner 用户能写。\n * - dir 可写 = 能以 runner 的身份执行任意代码;logDir 可写 = 能往任务日志里追加内容\n * - 属主不是当前用户、或 group/other 有写位,都直接报错(不是告警)\n * - root 除外:root 能写任何目录,这条检查对 root 没有意义\n */\nconst checkDirPermissions = (cx: CronjobContext) => {\n if (typeof process.getuid !== 'function' || process.getuid() === 0) {\n return;\n }\n for (const [name, dir] of [\n ['dir', cx.dir],\n ['logDir', cx.logDir],\n ] as const) {\n const { mode, uid } = statSync(dir);\n const writableByOthers = (mode & 0o022) !== 0;\n if (uid !== process.getuid() || writableByOthers) {\n throw new Error(\n `${name} must be owned by the current user and not group/world-writable: ${dir} ` +\n `(owner=${uid}, mode=${(mode & 0o777).toString(8)})`,\n );\n }\n }\n};\n\n/** 写日志时用:任务输出可能含密钥,不让同机其他用户读 */\nexport const LOG_FILE_MODE = 0o640;\n\n/**\n * 锁名用的目录标识:realpath 兜住符号链接(/a/link 与 /b/real 是同一个目录时也能识别),\n * 目录还不存在时退回 resolve 的结果(ensureDir 在拿锁之后才建目录)。\n */\nconst lockKeyOf = (dir: string) => {\n try {\n return realpathSync(dir);\n } catch {\n return resolve(dir);\n }\n};\n\n/**\n * 绑定成功则 resolve(进程活着就一直占着);\n * 已被占用则 reject —— 不 process.exit,由宿主决定怎么退。\n * @returns {Promise<void>}\n */\nconst acquireLock = (cx: CronjobContext) =>\n new Promise<void>((resolve, reject) => {\n /**\n * 锁名跟着任务目录走,同一台机器跑多个项目时不会互相误伤。\n * \\0 前缀 = 抽象 namespace,不落盘;进程退出(含 kill -9)由内核自动释放。\n * exclusive: true —— cluster 模式下 listen 默认交给 primary 代绑并共享句柄,\n * 每个 worker 都会\"成功\",锁就失效了;exclusive 让每个 worker 自己真绑,第二个拿到 EADDRINUSE。\n */\n const LOCK_NAME = '\\0krontab-' + createHash('sha1').update(lockKeyOf(cx.dir)).digest('hex').slice(0, 8);\n const server = net.createServer();\n server.once('error', (e: NodeJS.ErrnoException) => {\n reject(e.code === 'EADDRINUSE' ? new Error('krontab already running') : e);\n });\n server.listen({ path: LOCK_NAME, exclusive: true }, () => {\n server.unref(); // 不阻止进程退出\n _lock = server;\n resolve();\n });\n });\n\nexport const initialize = async (cx: CronjobContext) => {\n // 先拿锁:重复实例不必再做后面的探测\n await acquireLock(cx);\n ensureDir(cx);\n checkDirPermissions(cx);\n orTsx(cx);\n orPython(cx);\n};\n","import type { Job } from './types/global.js';\nimport type { CronjobContext } from './types/config.js';\n\nimport { spawn } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { env } from 'node:process';\n\nimport { CMD_NONE } from './context/interpreter.js';\nimport { LOG_FILE_MODE } from './initialize.js';\n\nexport function run(cx: CronjobContext, { filepath, interpreter }: Job) {\n let output: number | null = null;\n const closeOutput = () => {\n if (output !== null) {\n fs.closeSync(output);\n output = null; // ! 防止反复close\n }\n };\n // 主日志统一用相对路径,绝对路径只用于 spawn\n const relativePath = path.relative(cx.dir, filepath);\n try {\n // 把相对于cron文件夹的路径也带入到日志路径中,这样符合直觉\n const logfile = path.join(cx.logDir, relativePath + '.log');\n\n // 子目录下的脚本,其日志子目录也要存在,否则 shell 重定向失败、命令不会执行\n fs.mkdirSync(path.dirname(logfile), { recursive: true });\n\n // 运行这个文件\n if (interpreter.cmd === CMD_NONE) {\n cx.log.warn(`path=${relativePath} unsupported extension`);\n return;\n }\n\n const cmd = interpreter.cmd;\n const args = interpreter.args.concat(filepath);\n\n output = fs.openSync(logfile, 'a', LOG_FILE_MODE);\n\n const child = spawn(cmd, args, {\n stdio: ['ignore', output, output],\n detached: true,\n env,\n // 子进程 cwd 默认和主程序一样,或者以--cwd=xxx录入\n cwd: cx.jobcwd(filepath),\n });\n\n child.on('error', (e) => {\n closeOutput();\n cx.log.err(`path=${relativePath} pid=${child.pid ?? '-1'}`, e);\n });\n child.on('spawn', () => {\n closeOutput();\n cx.log.spawn(`path=${relativePath} pid=${child.pid ?? '-1'}`);\n });\n child.on('exit', (code, signal) => {\n closeOutput();\n cx.log.exit(`path=${relativePath} pid=${child.pid ?? '-1'} code=${code} signal=${signal}`);\n });\n child.unref();\n } catch (e) {\n closeOutput();\n // spawn 之前的异常(mkdir/openSync/jobcwd 等)也要进主日志,否则无法定位\n cx.log.err(`path=${relativePath} pid=-1`, e);\n }\n}\n","import path from 'node:path';\n\nimport type { CronjobContext } from './types/config.js';\nimport { tryGlobSync } from './utils.js';\nimport { loadFiles } from './syntax/job.js';\nimport { getJobItem } from './syntax/extract.js';\nimport { parseExp } from './cron/parse.js';\n\n/**\n * 罗列所有定时表达式,效果类似 `crontab -l`\n *\n * 输出四列:下次运行时间、表达式、相对路径、解释器命令\n * - 块内的多条表达式会缩进显示,并标出 group\n * - 同一条表达式每次都重新 parse,避免 next() 改动共享对象的内部游标\n */\nexport async function list(cx: CronjobContext) {\n const filepaths = tryGlobSync(cx);\n if (!filepaths) {\n return;\n }\n if (filepaths.length === 0) {\n cx.log.info(`No scripts found in ${cx.dir}`);\n return;\n }\n\n const files = await loadFiles(cx, filepaths);\n\n for (const f of files) {\n const relativePath = path.relative(cx.dir, f.filepath);\n\n if (f.error) {\n cx.log.err(`Error loading file ${relativePath}: ${f.error}`);\n continue;\n }\n if (f.content === null) {\n // 非普通文件:readHeader 已经记过 WARN\n continue;\n }\n\n const item = getJobItem(cx, f.filepath, f.content);\n if (!item) {\n continue;\n }\n\n if (item.flatCronGroups.length === 0) {\n cx.log.warn(`No cron expression: ${relativePath}`);\n continue;\n }\n\n const invocation = [item.interpreter.cmd, ...item.interpreter.args, relativePath].join(' ');\n\n for (const { cron, group, timezone } of item.flatCronGroups) {\n const exp = cron.stringify();\n const next = nextRunText(cx, exp, f.filepath, timezone);\n const prefix = (group > 0 ? ` [${group}] ` : '') + (timezone === 'UTC' ? 'UTC ' : '');\n console.log(`${next.padEnd(24)} ${(prefix + exp).padEnd(18)} ${relativePath.padEnd(32)} ${invocation}`);\n }\n }\n}\n\n/** 表达式在上一次 parse 后可能因 impossible date 抛错,这里只展示、不中断整个列表 */\nfunction nextRunText(cx: CronjobContext, exp: string, filepath: string, timezone: string) {\n const parsed = parseExp(cx, exp, filepath, timezone);\n if (!parsed) {\n return '(invalid)';\n }\n try {\n return cx.timeFormat.format(parsed.next().toDate());\n } catch {\n return '(no next run)';\n }\n}\n","/**\n * # 全局定时任务主理,以每分钟读取来决定是否运行\n * # 1. 只支持:【分 时 日 月 周】 的写法\n * # 2. cron 表达式写在脚本的文件头注释区(第一条正式代码之前的注释),以注释给出\n */\nimport type { UserCronjobConfig } from './types/config.js';\nimport { performance } from 'node:perf_hooks';\n\nimport { createContext } from './context/index.js';\nimport { CronjobState } from './consts.js';\nimport { tryGlobSync } from './utils.js';\nimport { runTask, type TaskController } from './cron/task.js';\nimport { getJobs, loadFiles } from './syntax/job.js';\nimport { run } from './run.js';\nimport { initialize } from './initialize.js';\nimport { list } from './list.js';\n\nexport type { TaskController } from './cron/task.js';\nexport { UserCronjobConfig };\n\n/**\n * 启动定时任务主理,返回控制器\n * - 只支持 5 段 cron:分 时 日 月 周\n * - 同一 dir 只允许一个实例\n */\nexport async function cronjob(config?: Partial<UserCronjobConfig>): Promise<TaskController> {\n const cx = createContext(config);\n cx.log.info(`Config loaded: ${JSON.stringify(cx)}`);\n\n if (process.argv.includes('--list') || process.argv.includes('-l')) {\n // 列出所有任务看一下效果就退出\n await list(cx);\n process.exit(0);\n }\n\n await initialize(cx);\n\n const taskFn = async (now: Date) => {\n // 1、查找CRONJOB_DIR下面的所有符合suffix的文件\n const filepaths = tryGlobSync(cx);\n if (!filepaths) {\n return;\n }\n if (filepaths.length === 0) {\n cx.log.info(`No scripts found.`);\n return;\n }\n\n const performanceNow = performance.now();\n cx.log.debug(`Start`);\n\n const files = await loadFiles(cx, filepaths);\n const jobs = await getJobs(cx, files, now);\n\n // 读文件期间可能被 stop() / pause()(F33):已不在 Running 就不再 spawn 这一轮\n if (cx.jobState === CronjobState.Stopped) {\n return;\n }\n\n for (let i = 0; i < jobs.length; i++) {\n for (let n = 0; n < jobs[i].count; n++) {\n if (cx.jobState === CronjobState.Running) {\n run(cx, jobs[i]);\n }\n }\n }\n\n cx.log.debug(`Finished in ${(performance.now() - performanceNow).toFixed(6)}ms`);\n };\n\n const task = runTask(cx, taskFn);\n\n cx.log.info(`Cronjob start! pid=${process.pid}`);\n\n return task;\n}\n"],"mappings":"A,keAuBO,IAAUoB,GAAV,SAAAC,EAAA,CACeA,EAAA,KAAA,QACCA,EAAA,MAAA,UAEAA,EAAA,MAAA,aACMA,EAAA,YAAA,eACRA,EAAA,IAAA,WACMA,EAAA,UAAA,aAGNA,EAAA,IAAA,WACMA,EAAA,UAAA,YAC1B,EAAA,CAAAD,IAAA,CAAA,CAAD,EC9BA,MAAME,EAAUC,GAAgBA,EAAI,SAAS,GAAG,GAAKA,EAAI,SAAS,IAAI,EAUtE,SAAgBC,EAAcD,EAA4B,CACxD,GAAID,EAAOC,CAAG,EACZ,OAAOf,EAAWe,CAAG,EAAIA,EAAM,KAEjC,IAAK,IAAME,KAAQb,EAAI,MAAQ,+BAAA,CAAgC,MAAMV,CAAS,EAC5E,GAAIuB,GAAOjB,EAAWJ,EAAKqB,EAAKF,CAAG,CAAC,EAClC,OAAOA,EAGX,OAAO,IACT,CAQA,SAAgBG,GAAgB,CAC9B,IAAMC,EAAQH,EAAc,KAAK,GAAKA,EAAc,SAAS,GAAK,QAAQ,SACpEI,EAAUL,IAA8B,CAAEA,MAAK,KAAM,CAAC,CAAE,GAExDM,EAA4C,CAChD,MAAOD,EAAOD,CAAK,EACnB,OAAQC,EAAOD,CAAK,EACpB,OAAQC,EAAOD,CAAK,EACpB,MAAOC,EAAO,QAAQ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G,CACT,C"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,76 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "krontab",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "krontab — a minimal crontab for JavaScript and TypeScript: write a 5-field cron expression in a script's header comment, and the script is spawned when it matches. Complete TypeScript types included.",
|
|
5
|
+
"description_zh": "krontab —— 极简的 JS 版 crontab:把 5 段 cron 写在脚本头部注释里,到点就运行;完整 TS 类型支持。",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"author": {
|
|
8
|
+
"name": "Kasukabe Tsumugi",
|
|
9
|
+
"email": "futami16237@gmail.com"
|
|
10
|
+
},
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=22.14.0"
|
|
14
|
+
},
|
|
15
|
+
"main": "./dist/index.cjs",
|
|
16
|
+
"module": "./dist/index.mjs",
|
|
17
|
+
"types": "./dist/index.d.cts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"import": {
|
|
21
|
+
"types": "./dist/index.d.mts",
|
|
22
|
+
"default": "./dist/index.mjs"
|
|
23
|
+
},
|
|
24
|
+
"require": {
|
|
25
|
+
"types": "./dist/index.d.cts",
|
|
26
|
+
"default": "./dist/index.cjs"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"./package.json": "./package.json"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist",
|
|
33
|
+
"README.md"
|
|
34
|
+
],
|
|
35
|
+
"homepage": "https://github.com/baendlorel/krontab#readme",
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "git+https://github.com/baendlorel/krontab.git"
|
|
39
|
+
},
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/baendlorel/krontab/issues"
|
|
42
|
+
},
|
|
43
|
+
"keywords": [
|
|
44
|
+
"krontab",
|
|
45
|
+
"crontab",
|
|
46
|
+
"cron",
|
|
47
|
+
"cronjob",
|
|
48
|
+
"scheduler",
|
|
49
|
+
"job",
|
|
50
|
+
"typescript",
|
|
51
|
+
"javascript",
|
|
52
|
+
"timezone"
|
|
53
|
+
],
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@types/node": "^26.6.6",
|
|
56
|
+
"oxlint": "^1.94.0",
|
|
57
|
+
"prettier": "^3.10.1",
|
|
58
|
+
"tsdown": "^0.23.7",
|
|
59
|
+
"tslib": "^2.9.1",
|
|
60
|
+
"tsx": "^4.23.15",
|
|
61
|
+
"typescript": "^7.0.2",
|
|
62
|
+
"vitest": "^5.1.1"
|
|
63
|
+
},
|
|
64
|
+
"dependencies": {
|
|
65
|
+
"cron-parser": "^5.10.6"
|
|
66
|
+
},
|
|
67
|
+
"scripts": {
|
|
68
|
+
"build": "tsdown",
|
|
69
|
+
"buildtsc": "tsc -p tsconfig.build.json",
|
|
70
|
+
"pub": "pnpm run build && tsx ./scripts/index.ts --publish",
|
|
71
|
+
"check": "tsc --noEmit -p tsconfig.json",
|
|
72
|
+
"lint": "oxlint .",
|
|
73
|
+
"test": "vitest run",
|
|
74
|
+
"test:watch": "vitest"
|
|
75
|
+
}
|
|
6
76
|
}
|