mirror of
https://github.com/directus/directus.git
synced 2026-04-25 03:00:53 -04:00
* 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>
44 lines
828 B
TypeScript
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 };
|
|
}
|