1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-01-06 00:07:44 +01:00
unleash.unleash/src/lib/services/scheduler-service.ts
Fredrik Strand Oseberg a71c3fe43a
feat: add ids to scheduled jobs (#4764)
* Adds an ID to scheduled jobs so that they are easier to identify in
the future
2023-09-18 16:31:42 +02:00

60 lines
1.4 KiB
TypeScript

import { Logger, LogProvider } from '../logger';
export type SchedulerMode = 'active' | 'paused';
export class SchedulerService {
private intervalIds: NodeJS.Timer[] = [];
private mode: SchedulerMode;
private logger: Logger;
constructor(getLogger: LogProvider) {
this.logger = getLogger('/services/scheduler-service.ts');
this.mode = 'active';
}
async schedule(
scheduledFunction: () => void,
timeMs: number,
id: string,
): Promise<void> {
this.intervalIds.push(
setInterval(async () => {
try {
if (this.mode === 'active') {
await scheduledFunction();
}
} catch (e) {
this.logger.error(
`scheduled job failed | id: ${id} | ${e}`,
);
}
}, timeMs).unref(),
);
try {
if (this.mode === 'active') {
await scheduledFunction();
}
} catch (e) {
this.logger.error(`scheduled job failed | id: ${id} | ${e}`);
}
}
stop(): void {
this.intervalIds.forEach(clearInterval);
}
pause(): void {
this.mode = 'paused';
}
resume(): void {
this.mode = 'active';
}
getMode(): SchedulerMode {
return this.mode;
}
}