krontab 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,12 +1,18 @@
1
1
  # krontab
2
2
 
3
+ <div align="center" style="margin:0 auto">
4
+ <img src="./assets/icon.svg" alt="krontab" width="200" height="200" />
5
+ </div>
6
+
7
+ English | [简体中文](README.zh.md)
8
+
3
9
  A minimal, JS-native crontab.
4
10
 
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.
11
+ Drop a script into a directory and write a 5-field cron expression in its header comment — krontab runs the script when the time comes.
6
12
 
7
- No retries, no catch-up runs, no overlap protection, no process supervision. If a job ran or not, read the log.
13
+ The name is `crontab` with a `K` — both "kron" (time) and the author's initial. The package still exports one function, `cronjob()`.
8
14
 
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)).
15
+ Beyond usage, also read [Design limits](#design-limits).
10
16
 
11
17
  ## Install
12
18
 
@@ -33,18 +39,16 @@ Valid cron expression:
33
39
  └───────────────────── minute (0-59)
34
40
  ```
35
41
 
36
- Create a job script:
42
+ Create a job script, `cronjob/backup.js`:
37
43
 
38
44
  ```js
39
- // cronjob/backup.js
40
45
  // @cron 0 3 * * * # 每天凌晨三点
41
46
  console.log('backup', new Date().toISOString());
42
47
  ```
43
48
 
44
- Start the runner from your project root:
49
+ Start the runner from your project root, in `main.js`:
45
50
 
46
51
  ```js
47
- // main.js
48
52
  import { cronjob } from 'krontab';
49
53
 
50
54
  const task = await cronjob({ dir: './cronjob' });
@@ -166,18 +170,16 @@ Six-field expressions are **not** supported:
166
170
  // @cron 0 0 9 * * * ← rejected, error logged, not scheduled
167
171
  ```
168
172
 
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
173
  ## Supported script types
172
174
 
173
- | Extension | Interpreter |
174
- | ---------------- | ------------------------------------------------------ |
175
- | `.js` / `.mjs` / `.cjs` | the current Node.js (`process.execPath`) |
175
+ | Extension | Interpreter |
176
+ | ----------------------- | ------------------------------------------------------ |
177
+ | `.js` / `.mjs` / `.cjs` | the current Node.js (`process.execPath`) |
176
178
  | `.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
+ | `.sh` | `bash`, falling back to `sh` |
180
+ | `.py` | `python3` → `python` |
179
181
 
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`.
182
+ `.mjs` / `.cjs` / `.mts` / `.cts` are matched by the default `include`, the same as `.ts` / `.js`; their header comments use the same `//` and `/** */` rules as `.js` / `.ts`.
181
183
 
182
184
  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
185
 
@@ -185,7 +187,7 @@ If a `.ts` file has a `#!` line, that shebang wins over the default interpreter.
185
187
 
186
188
  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
189
 
188
- `.py` is only used if you add it to `include`; the default glob does not match it.
190
+ The default glob matches `.py` as well, so Python jobs run out of the box.
189
191
 
190
192
  ## Logs
191
193
 
@@ -242,26 +244,21 @@ The lock name is derived from `dir`, so it is predictable; any local process tha
242
244
 
243
245
  ### `UserCronjobConfig`
244
246
 
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`. |
247
+ | Option | Type | Default | Description |
248
+ | ---------- | ------------------------------------------ | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
249
+ | `dir` | `string` | `process.cwd()` | Directory scanned for job scripts. Created if missing. |
250
+ | `logDir` | `string` | same as `dir` | Where per-job logs are written. Created if missing. |
251
+ | `include` | `string[]` | `['**/*.{ts,js,sh,cts,mts,cjs,mjs,py}']` | Glob patterns for job scripts (passed to `fs.glob`). |
252
+ | `exclude` | `string[]` | see below | Glob patterns to skip (passed to `fs.glob` as `exclude`). |
253
+ | `timezone` | `string` | `'Asia/Shanghai'` | IANA timezone used for cron matching and for the `timeFormat` timestamps. See [Daylight saving time](#daylight-saving-time). |
254
+ | `jobcwd` | `string \| (scriptPath: string) => string` | same as `dir` | Working directory for spawned jobs. Pass a function to derive it per script. |
255
+ | `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
256
 
255
257
  Invalid config throws a `TypeError` naming the option (`dir`, `logDir`, `include`, …); an unknown `timezone` throws a `RangeError` from `Intl.DateTimeFormat`.
256
258
 
257
259
  #### Daylight saving time
258
260
 
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.
261
+ Matching is done purely against the expression, so if you hit a clock jump, switch that schedule to `@cronutc`.
265
262
 
266
263
  #### Default `exclude`
267
264
 
@@ -313,15 +310,15 @@ At startup the runner also warns about a missing `tsx` (only matters for `.ts`)
313
310
 
314
311
  These are deliberate, not missing features:
315
312
 
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.
313
+ - **No retries.** There is no way to know whether the failure happened before or after a side effect, so noticing a failure should be the job author's own responsibility.
314
+ - **No catch-up.** If the machine was down at 03:00, the 03:00 job does not run when it comes back — purely because that time never arrived.
315
+ - **Overlap happens.** A long job will overlap with its next run.
316
+ - **No process management.** krontab does not watch or kill job processes; it should not take control of things that are not its own.
317
+ - **No exit-code alerts.** Every exit is logged; read the log if you care.
318
+ - **No job lifecycle hooks.** There is no callback for "job started" or "job finished"; a minimal scheduler should not have them.
322
319
  - **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
320
 
324
- The runner itself is kept alive by pm2. If the runner dies, nothing runs until pm2 restarts it.
321
+ krontab itself is best kept alive by pm2. If the runner dies, nothing runs until pm2 restarts it.
325
322
 
326
323
  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
324
 
package/README.zh.md ADDED
@@ -0,0 +1,329 @@
1
+ # krontab
2
+
3
+ <div align="center" style="margin:0 auto">
4
+ <img src="./assets/icon.svg" alt="krontab" width="200" height="200" />
5
+ </div>
6
+
7
+ [English](README.md) | 简体中文
8
+
9
+ 极简的 JS 原生 crontab。
10
+
11
+ 把一个脚本放进目录,在它的头部注释里写 5 段 cron 表达式 —— krontab 会在时间到来之际运行这个脚本。
12
+
13
+ 名字是 `crontab` 的 K 写法:既指 "kron"(时间),也是作者名字的首字母。包仍然只导出一个函数 `cronjob()`。
14
+
15
+ 除了使用方法之外,还需注意[设计边界](#设计边界)
16
+
17
+ ## 安装
18
+
19
+ ```bash
20
+ pnpm add krontab
21
+ # 或
22
+ npm i krontab
23
+ ```
24
+
25
+ 需要 **Node.js >= 22.14.0**。
26
+
27
+ ## 快速开始
28
+
29
+ 合法的 cron 表达式:
30
+
31
+ ```text
32
+ * * * * *
33
+ ┬ ┬ ┬ ┬ ┬
34
+ │ │ │ │ │
35
+ │ │ │ │ └─ 星期(0-7,1L-7L)(0 或 7 是周日)
36
+ │ │ │ └────── 月(1-12,JAN-DEC)
37
+ │ │ └─────────── 日(1-31,L)
38
+ │ └──────────────── 时(0-23)
39
+ └───────────────────── 分(0-59)
40
+ ```
41
+
42
+ 创建一个任务脚本:
43
+
44
+ 对于cronjob/backup.js
45
+ ```js
46
+ // @cron 0 3 * * * # 每天凌晨三点
47
+ console.log('backup', new Date().toISOString());
48
+ ```
49
+
50
+ 在项目根目录启动 runner:
51
+
52
+ 对于外面的main.js
53
+ ```js
54
+ import { cronjob } from 'krontab';
55
+
56
+ const task = await cronjob({ dir: './cronjob' });
57
+ ```
58
+
59
+ 交给 pm2 保活:
60
+
61
+ ```bash
62
+ pm2 start main.js --name cronjob --log cronjob-runner/main.log --no-treekill
63
+ ```
64
+
65
+ > **务必保留 `--no-treekill`。** pm2 默认会杀掉整棵进程树。任务虽然是 detached + unref 的,但仍然挂在 pm2 的进程树里,所以 `pm2 restart` / `pm2 stop` 会把还在跑的任务一起杀掉 —— 而且拿不到 `[EXIT]` 行,因为 runner 先退出了。加上 `--no-treekill`(或在 ecosystem 里写 `treekill: false`)后,正在跑的任务能在部署中存活。runner 还是单实例守护进程:用 fork 模式启动,不要用 `-i`(见下文)。
66
+
67
+ `cronjob()` 返回一个控制器,带 `stop()` / `pause()` / `resume()`。
68
+
69
+ 想只看会跑什么、不真的启动调度,给同一个脚本传 `--list`(或 `-l`):
70
+
71
+ ```bash
72
+ node main.js --list
73
+ ```
74
+
75
+ 它每条调度打印一行然后退出,此时还没有拿单实例锁:
76
+
77
+ ```
78
+ 2026/11/22 03:00:00.000 0 3 * * * backup.js /usr/bin/node backup.js
79
+ ```
80
+
81
+ 四列分别是 **下次运行时间**(用 `timezone` 格式化)、**表达式**(块内成员缩进并标 `[group]`)、**相对 `dir` 的路径**、**将要 spawn 的命令**。`--list` 走同一个 `write`,所以表前面照例有 `[INFO] Config loaded: …` 一行。行序跟随 glob 顺序(同一目录内大致按字母序),不按下次运行时间排序。
82
+
83
+ 没有 `@cron` 行的文件会输出 `[WARN] No cron expression: <路径>` 而不是一行表格。能解析但没有下次触发时间的表达式在时间列显示 `(no next run)`;在这一步解析失败的显示 `(invalid)`。实际上提取阶段只保留已经解析成功的表达式,所以写坏的行会更早被丢掉,到不了这张表。什么都没找到时输出 `[INFO] No scripts found in <dir>` 后退出。
84
+
85
+ `--list` 由 `cronjob()` 扫描 `process.argv` 判断,所以任何含 `--list` 或 `-l` 的参数都会被当成这个分支 —— 包括你本来想传给自己的程序的参数。不要把这两个 flag 透传下去。
86
+
87
+ ## 编写任务
88
+
89
+ cron 表达式写在**文件头注释**里 —— 从第 1 行到第一行正式代码之前。`.ts`/`.js` 用 `//` 或 `/** */`,`.sh` 用 `#`。头部里的空行和其它注释行都没问题,不会结束文件头。在 `/* */` 块里,每一行正文都必须以 `*` 开头 —— 这是通行写法(也是大多数编辑器和格式化工具的输出)。正文没有 `*` 前缀的 `/*` 块**不算**文件头:第一行这样的内容就结束文件头,于是看不到 `@cron`,文件静默地不被调度。
90
+
91
+ `@cronbegin` / `@cronend` 在文件头的**任意位置**匹配,包括说明文字。仅仅提到它们的注释(如 `// 参见 @cronend`)会被当成标记,导致整个文件因块错误被拒绝、不予调度。这是刻意的:解析失败的文件永远不跑,比猜作者意图更安全。写说明时别把这两个词留在文件头里。
92
+
93
+ `@cronutc` 就是 `@cron`,同样接 5 段表达式,但这条按 **UTC** 匹配,而不是 `timezone`。它是行内标记:只作用于所在行,不改变其它行的匹配方式。当某个调度不能随夏令时漂移时用它:
94
+
95
+ ```js
96
+ // @cron 0 9 * * * 每天九点(按 timezone)
97
+ // @cronutc 0 9 * * * 每天 09:00 UTC
98
+ ```
99
+
100
+ 5 段之后的内容仍然是说明文字,`@cronutc` 在 `@cronbegin` / `@cronend` 块内也照常可用。`--list` 会给这些行加 `UTC` 前缀。
101
+
102
+ 两个标记都在整行内匹配、包括说明文字,所以文件头的一行里不能出现 `@cronutc`,除非它就是这一行的标记。把两个标记写在同一行(`// @cron 0 9 * * * 也可以写成 @cronutc`)是有歧义的 —— 该行记一条 `[ERROR]` 且不调度。别把 `@cronutc` 留在说明里。
103
+
104
+ `.py` 的文件头可以用 `#` 注释。`@cron` 必须写在某条 `#` 行上;`'''` / `"""` 文档字符串的定界行可以出现在文件头里,但**文档字符串正文行不会被扫描**,所以多行文档字符串里的 `@cron` 会被忽略。Python 任务请用 `# @cron …`。
105
+
106
+ ```js
107
+ // @cron 0 9 * * *
108
+ // @cron 30 18 * * 1-5 工作日下班
109
+ console.log('two independent schedules in one file');
110
+ ```
111
+
112
+ ```sh
113
+ #!/bin/bash
114
+ # @cron */5 * * * *
115
+ echo "every five minutes"
116
+ ```
117
+
118
+ 规则:
119
+
120
+ - 只支持 **5 段**:`分 时 日 月 周`。
121
+ - `@cron` 之后按空白切出的前 5 个 token 是表达式,之后全是说明文字、会被忽略。
122
+ - 没有 `@cron` 的行静默忽略。
123
+ - 字段语法来自 [cron-parser](https://github.com/harrisiirak/cron-parser):范围、列表、步长,以及星期字段里的 `MON-FRI` 这类名字。
124
+ - **不接受** `@daily`、`@hourly` 这类别名 —— 它们不是 5 段表达式。
125
+
126
+ 标记不必在行首:`// 说明 @cron 0 9 * * *` 是有效的,标记之前的文字会被忽略。
127
+
128
+ ### 关于表达式后面的说明文字
129
+
130
+ 既然 5 段之后都是说明,那么**能被 cron-parser 读懂的第 6 个 token** 会让这一行看起来像秒级表达式,因而被拒绝:
131
+
132
+ ```js
133
+ // @cron 0 9 * * * 1 ← 被解析成 6 段(秒级)cron → 报错,不调度
134
+ ```
135
+
136
+ 判断方式是:取前 6 个 token 尝试解析。成功则以 `6 fields cron is not supported, use 5 fields instead` 跳过该行;失败则前 5 段照常调度,之后全是说明。所以 cron-parser 解析不了的任何东西都可以当说明:
137
+
138
+ ```js
139
+ // @cron 0 9 * * * 每天 ← 中文说明,6 段解析失败 → 5 段 + 说明
140
+ // @cron 0 9 * * * # 1 ← "#" 不是字段 → 5 段 + 说明
141
+ // @cron 0 9 * * * - 1 ← 同上
142
+ // @cron 0 9 * * * extra words ← "extra" 不是别名 → 5 段 + 说明
143
+ ```
144
+
145
+ ### 同一个文件里的多条调度
146
+
147
+ 每条 `@cron` 独立调度 —— 同一分钟命中两条,脚本就会被 spawn 两次:
148
+
149
+ ```js
150
+ // @cron 0 9 * * *
151
+ // @cron 0 21 * * *
152
+ ```
153
+
154
+ 想要「命中任意一条,但只跑一次」时用块:
155
+
156
+ ```js
157
+ // @cronbegin
158
+ // @cron 0 9 * * 1-5
159
+ // @cron 0 9 * * 6
160
+ // @cronend
161
+ ```
162
+
163
+ 块内任意一行命中,文件只 spawn **一次**。块按出现顺序编号,各块独立计数 —— 同一分钟两个块都命中,文件会被 spawn 两次。不在任何块里的行不分组,各自独立调度。
164
+
165
+ `@cronbegin` 和 `@cronend` 必须各自独占一行。一行的分类顺序是 begin → end → 表达式,所以 `@cronbegin @cron 0 9 * * *` 只会开一个块,**丢弃这一行的表达式**;请把它们写在不同的行。块嵌套、块未闭合、`@cronend` 没有对应的 begin,都会导致整个文件被跳过并记一条错误日志。块内某行没有 `@cron` 标记时会记一条 `[WARN]`,因为它很可能是本想写成调度的注释。
166
+
167
+ ### 不支持秒级表达式
168
+
169
+ 不支持 6 段表达式:
170
+
171
+ ```js
172
+ // @cron 0 0 9 * * * ← 拒绝、记错误、不调度
173
+ ```
174
+
175
+ ## 支持的脚本类型
176
+
177
+ | 扩展名 | 解释器 |
178
+ | ----------------------- | ------------------------------------------- |
179
+ | `.js` / `.mjs` / `.cjs` | 当前 Node.js(`process.execPath`) |
180
+ | `.ts` / `.mts` / `.cts` | `tsx` → `ts-node` → 用 Node.js 原生类型擦除 |
181
+ | `.sh` | `bash`,找不到则退回 `sh` |
182
+ | `.py` | `python3` → `python` |
183
+
184
+ `.mjs` / `.cjs` / `.mts` / `.cts` 和 `.ts` / `.js` 一样被默认 `include` 匹配;它们的头部注释规则与 `.js` / `.ts` 相同,都用 `//` 和 `/** */`。
185
+
186
+ 没有任何解释器映射的扩展名,只有在脚本被提取出来时才会走到;实践中未知扩展名没有可用于头部的注释语法,所以找不到 `@cron` 行,什么都不会 spawn。万一走到那一步,会记一条 `[WARN] path=… unsupported extension`。
187
+
188
+ 如果 `.ts` 文件有 `#!` 行,shebang 优先于默认解释器,其它扩展名同理。shebang 按 `命令 参数...` 解析,所以 `#!/usr/bin/env node` 执行的是 `/usr/bin/env node <脚本>`,`#!/bin/bash -e` 执行的是 `/bin/bash -e <脚本>`。
189
+
190
+ 没有安装 `tsx` 时,`.ts` 仍会由 Node.js 直接运行,但不是所有 TypeScript 语法都支持 —— 启动时会记一条警告。
191
+
192
+ 默认 glob 也会匹配 `.py`,Python 任务开箱即用。
193
+
194
+ ## 日志
195
+
196
+ 所有内容都写到 runner 的 stdout(用 `pm2 --log` 持久化),另外每个任务还有一个日志文件:
197
+
198
+ - **主日志**:每个事件一行 —— `[INFO]`、`[WARN]`、`[ERROR]`、`[SPAWN]`、`[EXIT]`、`[DEBUG]`。三条任务生命周期日志是:
199
+
200
+ ```
201
+ 2026/11/21 09:00:00.017 [SPAWN] path=daily/report.js pid=12345
202
+ 2026/11/21 09:00:04.210 [EXIT] path=daily/report.js pid=12345 code=0 signal=null
203
+ 2026/11/21 09:00:00.018 [ERROR] path=daily/report.js pid=-1 Error: spawn ENOENT
204
+ ```
205
+
206
+ 进程根本没启动起来时,`[ERROR]` 用 `pid=-1`。
207
+ - **时间戳**是 `timezone` 下的 `yyyy/MM/dd HH:mm:ss.SSS`(即 `zh-CN` 的 `Intl.DateTimeFormat` 输出)。
208
+ - **任务日志**:`<logDir>/<相对路径>.log`,追加写入,`.log` 后缀接在完整文件名之后(`daily/report.js` → `<logDir>/daily/report.js.log`)。任务自己的 stdout/stderr 都写这里;pid 只出现在主日志里。
209
+ - **调试**:每轮只要至少找到一个脚本,就用 `[DEBUG] Start` / `[DEBUG] Finished in Nms` 包起来。`dir` 里没有匹配脚本时改为输出 `[INFO] No scripts found.`,不输出这一对。
210
+
211
+ 主日志里的 `path` 始终相对 `dir`。
212
+
213
+ 替换 `write` 可以把主日志送到别处(文件、logger、pm2 的 stdout)。它收到的 tag 已经是 `[INFO]` 这种格式:
214
+
215
+ ```js
216
+ await cronjob({
217
+ dir: './cronjob',
218
+ write(tag, ...args) {
219
+ myLogger.log(tag, ...args);
220
+ },
221
+ });
222
+ ```
223
+
224
+ ## API
225
+
226
+ ### `cronjob(config?): Promise<TaskController>`
227
+
228
+ 启动按分钟调度的 runner。启动时立刻按 `dir` 的哈希拿一个单实例锁 —— 同一目录上的第二个 runner 会抛 `krontab already running`。锁是一个抽象 Unix socket,进程退出(包括 `SIGKILL`)时由操作系统释放。
229
+
230
+ 如果 `process.argv` 含有 `--list` 或 `-l`,`cronjob()` 打印调度表后调用 `process.exit(0)`,不启动调度;这个分支不拿锁。
231
+
232
+ ### 权限
233
+
234
+ 启动时 `cronjob()` 会检查 `dir` 和 `logDir` 的属主是当前用户,且**不能是 group 或 world 可写**,否则抛错、不启动。它自己创建的目录固定用 `0755`,不受 umask 影响,所以在 `umask 002` 的机器(Debian/Ubuntu 的 `USERGROUPS_ENAB`)和 `022` 的机器上都能通过检查。这两个目录都等价于「以 runner 用户身份执行代码」—— 能写 `dir` 的人可以投放脚本,能写 `logDir` 的人可以往任务日志里追加内容。`/tmp` 这类共享目录按设计被拒绝。自定义日志文件以 `0640` 创建;已存在的文件追加写入、不改动其 mode。以 root 运行时跳过检查(root 哪里都能写,检查没有意义),没有 `process.getuid` 的平台(Windows)同样跳过。
235
+
236
+ 检查只覆盖 **`dir` 和 `logDir` 本身** —— 不向上检查父目录,也不重新检查子目录:
237
+
238
+ - 父目录是 world 可写也能通过:`/srv/shared` 是 `777`、其下的 `jobs` 是 `755` 时,其他用户可以把 `jobs` 改名移走,再放一个自己的目录到原位。
239
+ - `dir` 内 world 可写的**子目录**也能通过:`dir/team` 是 `777` 时,`team/x.js` 照样会被 glob 到并 spawn。
240
+
241
+ 扫描哪些目录是安全的,交给部署方决定:`dir` 及其下所有目录只让 runner 用户可写。
242
+
243
+ 锁名由 `dir` 推导而来,因此可预测;本机任何进程只要先绑上这个抽象 socket,runner 就会报 `krontab already running`。最坏情况是本机拒绝服务 —— 它无法让 runner 执行任何东西。
244
+
245
+ > **从 `cronjob-js` 升级:** 锁名已从 `cronjob-js-…` 改为 `krontab-…`。如果同一个 `dir` 上还有旧 runner 在跑,新的 runner **不会**检测到它,两个都会调度。请先停掉旧进程再启动新的。
246
+
247
+ ### `UserCronjobConfig`
248
+
249
+ | 选项 | 类型 | 默认值 | 说明 |
250
+ | ---------- | ------------------------------------------ | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
251
+ | `dir` | `string` | `process.cwd()` | 扫描任务脚本的目录,不存在则创建。 |
252
+ | `logDir` | `string` | 与 `dir` 相同 | 任务日志目录,不存在则创建。 |
253
+ | `include` | `string[]` | `['**/*.{ts,js,sh,cts,mts,cjs,mjs,py}']` | 匹配任务脚本的 glob(传给 `fs.glob`)。 |
254
+ | `exclude` | `string[]` | 见下文 | 排除的 glob(作为 `exclude` 传给 `fs.glob`)。 |
255
+ | `timezone` | `string` | `'Asia/Shanghai'` | 用于 cron 匹配和 `timeFormat` 时间戳的 IANA 时区。见[夏令时](#夏令时)。 |
256
+ | `jobcwd` | `string \| (scriptPath: string) => string` | 与 `dir` 相同 | spawn 出来的任务的 cwd。传函数可以按脚本路径动态决定。 |
257
+ | `write` | `(tag: Tag, ...args: any[]) => void` | `console.log(time, tag, ...args)` | 主日志的输出位置。`tag` 是 `[INFO]` `[WARN]` `[ERROR]` `[SPAWN]` `[EXIT]` `[DEBUG]` 之一。默认写 stdout,时间戳用 `timezone`。 |
258
+
259
+ 非法配置会抛 `TypeError` 并指明选项名(`dir`、`logDir`、`include` 等);未知的 `timezone` 会由 `Intl.DateTimeFormat` 抛 `RangeError`。
260
+
261
+ #### 夏令时
262
+
263
+ 由于完全按照表达式匹配,因此如果碰到时间跳变问题,请改为 `@cronutc` 来解决。
264
+
265
+ #### 默认 `exclude`
266
+
267
+ ```js
268
+ [
269
+ '**/node_modules/',
270
+ '**/.git/',
271
+ '**/.vscode/',
272
+ '**/.claude/',
273
+ '**/__pycache__/',
274
+ '**/dist/',
275
+ '**/dist-tsc/',
276
+ '**/coverage/',
277
+ ];
278
+ ```
279
+
280
+ `**/` 很重要:只写 `'node_modules/'` 只能匹配 `dir` 根目录下的那一个,所以放在 `jobs/node_modules/` 里的第三方子项目仍会被扫描、每分钟读一次。点号开头的目录(`.git`、`.vscode`、`.claude`)本来就会被 `fs.glob` 跳过;列出来是为了让显式覆盖 `exclude` 时不会意外把它们重新纳入。`dist`、`dist-tsc`、`coverage` 是常见的构建产物,不排除的话会被当作任务脚本 glob 出来并读取。
281
+
282
+ 替换 `exclude` 就是整体替换这份列表 —— 不会合并。
283
+
284
+ ### `TaskController`
285
+
286
+ ```ts
287
+ interface TaskController {
288
+ stop(): void; // 清掉待触发的定时器,状态置为 Stopped;之后再 resume() 无效
289
+ pause(): void; // 定时器继续走,但不执行回调
290
+ resume(): void; // 恢复被暂停的 runner
291
+ }
292
+ ```
293
+
294
+ ## 工作原理
295
+
296
+ 每分钟 runner 会:
297
+
298
+ 1. 在 `dir` 里 glob 匹配的文件,
299
+ 2. 读取每个文件的头部注释块,
300
+ 3. 用 `cron-parser` 按 `timezone` 解析 `@cron` 行,
301
+ 4. spawn 命中的脚本,detached + unref,stdout/stderr 重定向到各自的日志文件。
302
+
303
+ 没有内存缓存:文件每分钟重新读取、重新解析,所以改掉脚本的 `@cron` 行会在下一轮生效,无需重启。
304
+
305
+ 第一次 tick 会对齐到下一个分钟边界。如果定时器早了几毫秒触发(WSL 上常见),它会等到边界再执行,而不是把同一分钟跑两次。
306
+
307
+ 下一轮会在本轮执行之前排好,所以读文件慢或任务抛错都不会打断调度链。tick 抛出的异常或被拒绝的 Promise 只会记一条 `[ERROR] Task tick failed:`,别的什么都不做 —— 下一分钟照常执行。
308
+
309
+ 启动时 runner 还会对缺失的 `tsx` 告警(只影响 `.ts`),并报告是否找到 `python3`/`python`(只在你 include 了 `.py` 时才有意义)。
310
+
311
+ ## 设计边界
312
+
313
+ 这些是刻意为之,不是缺功能:
314
+
315
+ - **不可以重试。** 无法知道失败是发生在副作用之前还是之后,所以提醒失败应该由任务作者自己完成。
316
+ - **不可以补跑。** 03:00 机器关着,开机后 03:00 的任务不会补跑,纯粹是因为时间没到。
317
+ - **会重叠。** 跑得久的任务会和它的下一次重叠。
318
+ - **不可以管理进程。** krontab 不会监控、也不会杀任务进程,因为不能额外去控制不属于自己的东西。
319
+ - **退出码不告警。** 退出都有日志,可以查看日志。
320
+ - **没有任务生命周期回调。** 没有「任务开始」「任务结束」的回调;极简的调度器不应该有这些。
321
+ - **定时器按分钟对齐,不是按秒。** 进程忙或主机跨边界挂起时,tick 会在事件循环轮到它时发生,漏掉的那一分钟不补。
322
+
323
+ krontab 本体非常适合用 pm2 保活。runner 死掉后,直到 pm2 把它重启,否则什么都不会跑。
324
+
325
+ 请用 pm2 的 **fork 模式**(默认)。用 `-i`(cluster 模式)时所有 worker 共享同一个任务目录;单实例锁只让第一个 worker 调度,其它的以 `krontab already running` 退出并被 pm2 反复重启。
326
+
327
+ ## 许可证
328
+
329
+ MIT —— 见 [LICENSE](LICENSE)。
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 64 64" fill="none">
2
+ <title>krontab</title>
3
+ <path d="M38 10.83A22 22 0 1 0 53.17 26" stroke="#171B22" stroke-width="4" stroke-linecap="round" />
4
+ <path d="M25 21V43M40 21L25 32L40 43" stroke="#171B22" stroke-width="4.5" stroke-linecap="round"
5
+ stroke-linejoin="round" />
6
+ <circle cx="48.5" cy="17.5" r="3" fill="#FF784F" />
7
+ </svg>
@@ -0,0 +1,12 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
2
+ <!-- 背景圆角方块 -->
3
+ <rect x="10" y="10" width="80" height="80" rx="18" fill="#0F172A"/>
4
+ <!-- 网格线(表格感) -->
5
+ <line x1="10" y1="38" x2="90" y2="38" stroke="#334155" stroke-width="1.5"/>
6
+ <line x1="10" y1="62" x2="90" y2="62" stroke="#334155" stroke-width="1.5"/>
7
+ <line x1="38" y1="10" x2="38" y2="90" stroke="#334155" stroke-width="1.5"/>
8
+ <!-- 字母 K -->
9
+ <path d="M30 28 L30 72 M30 50 L58 28 M30 50 L58 72" fill="none" stroke="#F59E0B" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/>
10
+ <!-- 一个代表“任务”的小点 -->
11
+ <circle cx="68" cy="50" r="4" fill="#38BDF8"/>
12
+ </svg>
@@ -0,0 +1,14 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
2
+ <!-- 背景圆 -->
3
+ <circle cx="50" cy="50" r="46" fill="#1E293B" />
4
+ <!-- 表盘外圈 -->
5
+ <circle cx="50" cy="50" r="38" fill="none" stroke="#38BDF8" stroke-width="3" />
6
+ <!-- 时钟刻度(12点、3点、6点、9点) -->
7
+ <line x1="50" y1="16" x2="50" y2="24" stroke="#94A3B8" stroke-width="2" stroke-linecap="round" />
8
+ <line x1="84" y1="50" x2="76" y2="50" stroke="#94A3B8" stroke-width="2" stroke-linecap="round" />
9
+ <line x1="50" y1="84" x2="50" y2="76" stroke="#94A3B8" stroke-width="2" stroke-linecap="round" />
10
+ <line x1="16" y1="50" x2="24" y2="50" stroke="#94A3B8" stroke-width="2" stroke-linecap="round" />
11
+ <!-- 字母 K 作为指针 -->
12
+ <path d="M42 32 L42 68 M42 50 L62 32 M42 50 L62 68" fill="none" stroke="#38BDF8" stroke-width="5"
13
+ stroke-linecap="round" stroke-linejoin="round" />
14
+ </svg>
@@ -0,0 +1,19 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
2
+ <!-- 背景 -->
3
+ <circle cx="50" cy="50" r="48" fill="#FFFFFF" />
4
+ <!-- 外圈刻度环 -->
5
+ <circle cx="50" cy="50" r="42" fill="none" stroke="#E2E8F0" stroke-width="2" />
6
+ <!-- 刻度 -->
7
+ <g stroke="#CBD5E1" stroke-width="2" stroke-linecap="round">
8
+ <line x1="50" y1="8" x2="50" y2="14" />
9
+ <line x1="92" y1="50" x2="86" y2="50" />
10
+ <line x1="50" y1="92" x2="50" y2="86" />
11
+ <line x1="8" y1="50" x2="14" y2="50" />
12
+ </g>
13
+ <!-- 强调弧(代表时间流转) -->
14
+ <path d="M50 8 A42 42 0 0 1 92 50" fill="none" stroke="#2563EB" stroke-width="4"
15
+ stroke-linecap="round" />
16
+ <!-- 字母 K -->
17
+ <path d="M36 28 L36 72 M36 50 L64 28 M36 50 L64 72" fill="none" stroke="#1E293B" stroke-width="7"
18
+ stroke-linecap="round" stroke-linejoin="round" />
19
+ </svg>