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

60 lines
1.4 KiB
TypeScript
Raw Normal View History

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