@appweaver/skill 0.0.0-stage → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,228 @@
1
+ # Scheduler
2
+
3
+ The scheduler module runs recurring tasks using cron expressions. Its driver, `CronScheduler` (provider `cron`) of
4
+ `@appweaver/cron`, wraps the [`cron`](https://github.com/kelektiv/node-cron) library and is selected when the package is
5
+ installed; without it, or with `SCHEDULER_PROVIDER=none`, no `Scheduler` is defined. Jobs auto-start on `addJob`
6
+ (controlled by `SCHEDULER_AUTO_START_JOB`) and are stopped gracefully on application shutdown.
7
+
8
+ An application of scheduled jobs needs no server: disable `@appweaver/web` (`APP_MODULES_DISABLED=@appweaver/web`), and
9
+ the cron jobs keep it running. `weaver run` sets `SCHEDULER_AUTO_START_JOB` to `false`, so a one-shot task never starts
10
+ the jobs.
11
+
12
+ ## Injecting Scheduler
13
+
14
+ ```ts
15
+ import { inject } from '@appweaver/core';
16
+ import { Scheduler } from '@appweaver/common';
17
+
18
+ const scheduler = inject(Scheduler);
19
+ const optional = inject(Scheduler, false); // undefined without a scheduler driver
20
+ ```
21
+
22
+ ---
23
+
24
+ #### `scheduler.addJob(jobParams)`
25
+
26
+ Registers a new cron job and returns a unique job ID. Jobs start immediately by default (see
27
+ `SCHEDULER_AUTO_START_JOB`).
28
+
29
+ **`JobParams` fields** (the same for every scheduler):
30
+
31
+ | Field | Type | Default | Description |
32
+ | ----------------- | ------------------------- | --------- | ---------------------------------------------------------------- |
33
+ | `cronTime` | `string \| Date` | — | Cron expression (optional leading seconds field) or exact `Date` |
34
+ | `onTick` | `() => unknown` | — | Function to execute on each tick |
35
+ | `name` | `string` | — | Name of the job in the logs and the telemetry (`reports:daily`) |
36
+ | `timeZone` | `string` | system TZ | IANA timezone (e.g. `'America/New_York'`) |
37
+ | `providerOptions` | `Record<string, unknown>` | — | Options of the driver, passed to `CronJob.from` by `cron` |
38
+
39
+ The `cron` driver waits for a tick to finish before the next one and logs the errors of a tick. Its other options
40
+ (`start` to override `SCHEDULER_AUTO_START_JOB` for one job, `runOnInit`, `errorHandler`) go to `providerOptions`.
41
+
42
+ Every run is the root span of its own OpenTelemetry trace, `scheduler <name>`, see [telemetry](./telemetry.md).
43
+
44
+ ```ts
45
+ const jobId = scheduler.addJob({
46
+ cronTime: '0 9 * * *', // every day at 9 AM
47
+ onTick: async () => {
48
+ await sendDailyDigest();
49
+ }
50
+ });
51
+ ```
52
+
53
+ **Cron expression cheat sheet:**
54
+
55
+ ```
56
+ ┌──────────── minute (0–59)
57
+ │ ┌────────── hour (0–23)
58
+ │ │ ┌──────── day of month (1–31)
59
+ │ │ │ ┌────── month (1–12)
60
+ │ │ │ │ ┌──── day of week (0–7, 0 and 7 = Sunday)
61
+ │ │ │ │ │
62
+ * * * * *
63
+ ```
64
+
65
+ | Expression | Meaning |
66
+ | -------------- | ------------------------ |
67
+ | `* * * * *` | Every minute |
68
+ | `*/15 * * * *` | Every 15 minutes |
69
+ | `0 * * * *` | Every hour (on the hour) |
70
+ | `0 9 * * *` | Every day at 9:00 AM |
71
+ | `0 9 * * 1-5` | Weekdays at 9:00 AM |
72
+ | `0 0 1 * *` | First day of every month |
73
+
74
+ ---
75
+
76
+ #### `scheduler.getJob(jobId)`
77
+
78
+ Returns the job of the driver (a `CronJob` of `cron`, typed by `Scheduler<Job>`), or `undefined` if not found.
79
+
80
+ ```ts
81
+ const job = scheduler.getJob(jobId);
82
+ logger.info(`Is running: ${job?.isActive}`);
83
+ ```
84
+
85
+ ---
86
+
87
+ #### `scheduler.startJob(jobId)`
88
+
89
+ Starts a stopped job. Returns `true` if started, `false` if the job does not exist.
90
+
91
+ ```ts
92
+ scheduler.startJob(jobId);
93
+ ```
94
+
95
+ ---
96
+
97
+ #### `scheduler.stopJob(jobId)`
98
+
99
+ Stops a running job without removing it. Returns `true` if stopped.
100
+
101
+ ```ts
102
+ await scheduler.stopJob(jobId);
103
+ ```
104
+
105
+ ---
106
+
107
+ #### `scheduler.startAll()`
108
+
109
+ Starts all registered jobs that are not yet active.
110
+
111
+ ```ts
112
+ scheduler.startAll();
113
+ ```
114
+
115
+ ---
116
+
117
+ #### `scheduler.stopAll()`
118
+
119
+ Stops all running jobs. Called automatically during application shutdown.
120
+
121
+ ```ts
122
+ await scheduler.stopAll();
123
+ ```
124
+
125
+ ---
126
+
127
+ #### `scheduler.removeJob(jobId)`
128
+
129
+ Stops and permanently removes a job. Returns `true` if removed.
130
+
131
+ ```ts
132
+ await scheduler.removeJob(jobId);
133
+ ```
134
+
135
+ ---
136
+
137
+ ## Configuration
138
+
139
+ | Key | Type | Default | Description |
140
+ | -------------------------- | -------- | -------- | ---------------------------------------------------------------------------------------- |
141
+ | `SCHEDULER_AUTO_START_JOB` | `bool` | `true` | Automatically start jobs when `addJob` is called |
142
+ | `SCHEDULER_PROVIDER` | `string` | `'auto'` | `auto` (`cron` with `@appweaver/cron`, otherwise none), `cron`, `none`, or a module path |
143
+
144
+ ---
145
+
146
+ ## Running on multiple instances
147
+
148
+ Every application instance runs its own cron jobs, so a job registered at startup runs once per instance. When it must
149
+ run once per tick (sending a digest, charging a subscription), guard it with a lock of the `Memory` provider configured
150
+ for Redis (`MEMORY_PROVIDER=redis`, the default when `@appweaver/redis` is installed, see
151
+ [configuration.md](./configuration.md#providers)). The `memory` provider locks
152
+ within one process only, so it guards nothing across instances.
153
+
154
+ ```ts
155
+ import { inject } from '@appweaver/core';
156
+ import { Memory, Scheduler } from '@appweaver/common';
157
+
158
+ inject(Scheduler).addJob({
159
+ cronTime: '0 8 * * *',
160
+ onTick: async () => {
161
+ try {
162
+ // One attempt, the instance that loses the race skips this tick
163
+ await inject(Memory).lock('job:daily-digest', {
164
+ expireMs: 10 * 60_000,
165
+ retryCount: 1
166
+ });
167
+ } catch {
168
+ return;
169
+ }
170
+ await sendDailyDigest();
171
+ }
172
+ });
173
+ ```
174
+
175
+ The lock is left to expire instead of being released, so an instance whose clock runs a little late cannot take it
176
+ again once the job has finished. Keep `expireMs` longer than the job and the clock drift between the instances, and
177
+ shorter than the interval between the ticks.
178
+
179
+ ---
180
+
181
+ ## Real-world example
182
+
183
+ Register all jobs at startup in a dedicated module:
184
+
185
+ ```ts
186
+ // src/jobs/index.ts
187
+ import { inject } from '@appweaver/core';
188
+ import { Scheduler } from '@appweaver/common';
189
+
190
+ export function registerJobs() {
191
+ const scheduler = inject(Scheduler);
192
+
193
+ // Send a daily digest every morning at 8 AM
194
+ scheduler.addJob({
195
+ cronTime: '0 8 * * *',
196
+ onTick: async () => {
197
+ await sendDailyDigest();
198
+ }
199
+ });
200
+
201
+ // Clean up expired sessions every 30 minutes
202
+ scheduler.addJob({
203
+ cronTime: '*/30 * * * *',
204
+ onTick: async () => {
205
+ await deleteExpiredSessions();
206
+ }
207
+ });
208
+
209
+ // Run a heavy report only on weekdays; don't auto-start, trigger manually
210
+ const reportJobId = scheduler.addJob({
211
+ cronTime: '0 2 * * 1-5',
212
+ providerOptions: { start: false },
213
+ onTick: async () => {
214
+ await generateWeeklyReport();
215
+ }
216
+ });
217
+
218
+ return { reportJobId };
219
+ }
220
+ ```
221
+
222
+ ```ts
223
+ // src/main.ts
224
+ const { reportJobId } = registerJobs();
225
+
226
+ // Start the report job manually when needed
227
+ scheduler.startJob(reportJobId);
228
+ ```