2023-01-11 16:15:53 +01:00
|
|
|
import { Logger, LogProvider } from '../logger';
|
|
|
|
|
|
|
|
export default class SchedulerService {
|
|
|
|
private intervalIds: NodeJS.Timer[] = [];
|
|
|
|
|
|
|
|
private logger: Logger;
|
|
|
|
|
|
|
|
constructor(getLogger: LogProvider) {
|
|
|
|
this.logger = getLogger('/services/scheduler-service.ts');
|
|
|
|
}
|
|
|
|
|
2023-01-12 11:26:59 +01:00
|
|
|
async schedule(
|
|
|
|
scheduledFunction: () => void,
|
|
|
|
timeMs: number,
|
|
|
|
): Promise<void> {
|
2023-01-11 16:15:53 +01:00
|
|
|
this.intervalIds.push(
|
|
|
|
setInterval(async () => {
|
|
|
|
try {
|
|
|
|
await scheduledFunction();
|
|
|
|
} catch (e) {
|
|
|
|
this.logger.error('scheduled job failed', e);
|
|
|
|
}
|
|
|
|
}, timeMs).unref(),
|
|
|
|
);
|
2023-01-12 11:26:59 +01:00
|
|
|
try {
|
|
|
|
await scheduledFunction();
|
|
|
|
} catch (e) {
|
|
|
|
this.logger.error('scheduled job failed', e);
|
|
|
|
}
|
2023-01-11 16:15:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
stop(): void {
|
|
|
|
this.intervalIds.forEach(clearInterval);
|
|
|
|
}
|
|
|
|
}
|