-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
46 lines (32 loc) · 975 Bytes
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { checkPendingCrons } from "./src/cron";
import { Cron, close, watchUpdateEvent } from "./src/database";
import { log } from "./src/log";
import { drain } from "./src/nats";
function wait(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
log("Starting cron service");
process.on("SIGINT", () => teardown());
process.on("SIGTERM", () => teardown());
async function teardown() {
log("Shutting down cron service");
await close();
await drain();
process.exit(0);
}
while (true) {
await checkPendingCrons();
const now = Date.now();
const next = await Cron.findNext();
const nextRun = next?.nextRun?.getTime();
if (!nextRun) {
log("No pending cron jobs, waiting for update event");
await watchUpdateEvent();
continue;
}
const delay = nextRun - now;
log("Next check in", delay, "ms");
const waitUpdate = watchUpdateEvent();
await Promise.race([wait(delay), waitUpdate]);
waitUpdate.abort();
}