blob: bf0a0be0300abfd2555469423502da831199127b (
plain)
| 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
 | export type CronCallback = (task: CronTask) => Promise<void>;
export interface CronTaskConfig {
  readonly name: string;
  readonly interval: number;
  readonly callback: CronCallback;
  readonly startNow?: boolean;
}
export class CronTask {
  #timerTag: number | null = null;
  constructor(public readonly config: CronTaskConfig) {
    if (config.interval <= 0) {
      throw new Error("Cron task interval must be positive.");
    }
    if (config.startNow === true) {
      this.start();
    }
  }
  get running(): boolean {
    return this.#timerTag != null;
  }
  start() {
    if (this.#timerTag == null) {
      this.#timerTag = setInterval(
        this.config.callback,
        this.config.interval,
        this,
      );
    }
  }
  stop() {
    if (this.#timerTag != null) {
      clearInterval(this.#timerTag);
      this.#timerTag = null;
    }
  }
}
 |