Files
directus/api/src/utils/schedule.ts
Nicola Krumschmidt 60be3c2b40 Add synchronization across horizontally scaled instances to schedule flows and hooks (#18584)
* Add synchronization to schedule flows and hooks

Fixes #15052

* Add changeset

* Add test

* Add to sequential list

* Fix spelling in changeset

---------

Co-authored-by: Pascal Jufer <pascal-jufer@bluewin.ch>
Co-authored-by: ian <licitdev@gmail.com>
2023-05-24 17:16:42 -04:00

44 lines
828 B
TypeScript

import cron from 'cron-parser';
import schedule from 'node-schedule';
import { SynchronizedClock } from '../synchronization.js';
export interface ScheduledJob {
stop(): Promise<void>;
}
export function validateCron(rule: string): boolean {
try {
cron.parseExpression(rule);
} catch {
return false;
}
return true;
}
export function scheduleSynchronizedJob(
id: string,
rule: string,
cb: (fireDate: Date) => void | Promise<void>
): ScheduledJob {
const clock = new SynchronizedClock(`${id}:${rule}`);
const job = schedule.scheduleJob(rule, async (fireDate) => {
const nextTimestamp = job.nextInvocation().getTime();
const wasSet = await clock.set(nextTimestamp);
if (wasSet) {
await cb(fireDate);
}
});
const stop = async () => {
job.cancel();
await clock.reset();
};
return { stop };
}