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