aboutsummaryrefslogtreecommitdiff
path: root/src/util/scheduler.ts
blob: 9f9f59491928c9b4668c1571010c6c437a0260bd (plain) (blame)
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
import * as TE from "fp-ts/lib/TaskEither";
import { pipe } from "fp-ts/lib/function";
import type { Schedule } from "../canary";

interface ScheduledJob {
  id: string;
  execute: TE.TaskEither<Error, boolean>;
  at: Date;
  schedule: Schedule;
}

type SchedulerState = ReadonlyArray<ScheduledJob>;

export const schedulerLoop =
  (state: SchedulerState): TE.TaskEither<Error, void> =>
  () => {
    const loop = (currentState: SchedulerState): TE.TaskEither<Error, void> =>
      pipe(
        executeDueJobs(currentState),
        delay(1000), // Delay for 1 second
        map((newState) => loop(newState)),
      );

    return loop(state)();
  };