import * as TE from "fp-ts/lib/TaskEither"; import { pipe, identity } from "fp-ts/lib/function"; import type { Job, Schedule } from "../canary"; import * as RA from "fp-ts/lib/ReadonlyArray"; import * as T from "fp-ts/lib/Task"; import type { Separated } from "fp-ts/lib/Separated"; interface ScheduledJob { id: string; execute: () => TE.TaskEither; at: Date; schedule: Schedule; } type SchedulerState = ReadonlyArray; const executeAll = ( jobs: ReadonlyArray>, ): T.Task, ReadonlyArray>> => pipe(jobs, RA.wilt(T.ApplicativePar)(identity)); export const schedulerLoop = (state: SchedulerState): TE.TaskEither => () => { const loop = ( currentState: SchedulerState, time: Date, ): TE.TaskEither => pipe( currentState, RA.filter((job) => job.at <= time), RA.map(({ execute }) => execute()), executeAll, //T.delay(1000), // Delay for 1 second // map((newState) => loop(newState)), ); return loop(state)(); };