Добавлен планировщик задач с помощью SchedulerRegistry

This commit is contained in:
Pavel Gnedov 2024-12-09 23:28:22 +07:00
parent 299d658979
commit f284d70d6b
2 changed files with 88 additions and 49 deletions

View file

@ -86,4 +86,21 @@ export class DashboardsService {
if (!data.docs) throw createAppError('DASHBOARDS_NOT_FOUND'); if (!data.docs) throw createAppError('DASHBOARDS_NOT_FOUND');
return data.docs.map((d) => ({ id: d.id, title: d.data.title })); return data.docs.map((d) => ({ id: d.id, title: d.data.title }));
} }
async findDashboardsByWidgetType(
widgetType: string,
): Promise<DashboardModel.Dashboard[]> {
const ds = await this.db.getDatasource();
const data = await ds.find({
selector: {
'data.widgets': {
$elemMatch: {
type: widgetType,
},
},
},
});
if (!data.docs) throw createAppError('DASHBOARDS_NOT_FOUND');
return data.docs;
}
} }

View file

@ -1,6 +1,13 @@
import { DashboardsService } from '@app/event-emitter/dashboards/dashboards.service';
import { Dashboard, Widget } from '@app/event-emitter/models/dashboard';
import { Injectable, Logger } from '@nestjs/common'; import { Injectable, Logger } from '@nestjs/common';
import { Cron, SchedulerRegistry } from '@nestjs/schedule';
import { CronJob } from 'cron';
export type Params = any; // TODO export type Params = {
query: any; // TODO: add type
schedule: string;
};
export type Report = { export type Report = {
id: string; id: string;
@ -11,63 +18,78 @@ export type Report = {
data: any; data: any;
}; };
export type Job = {
id: string;
params: Params;
};
export const WIDGET_TYPE = 'daily-eccm-v2';
export const JOB_PREFIX = 'daily_eccm_v2';
@Injectable() @Injectable()
export class DailyEccmV2ReportService { export class DailyEccmV2ReportService {
private logger = new Logger(DailyEccmV2ReportService.name); private logger = new Logger(DailyEccmV2ReportService.name);
private jobs: any[] = []; private dashboardsService: DashboardsService;
addJob(job: any) { constructor(private schedulerRegistry: SchedulerRegistry) {}
this.logger.log(`Adding job ${job.id}`);
this.jobs.push(job);
}
getJobs() { @Cron('* * * * *')
this.logger.log('Getting all jobs'); async autoScanJobs() {
return this.jobs; this.logger.debug('Auto scan jobs started');
} const dbs = this.getDashboardsService();
if (!dbs) {
getJob(jobId: string) { this.logger.warn('Dashboards service not initialized');
this.logger.log(`Getting job ${jobId}`); this.logger.debug('Auto scan jobs finished');
return this.jobs.find((job) => job.id === jobId); return;
}
removeJob(jobId: string) {
this.logger.log(`Removing job ${jobId}`);
this.jobs.splice(this.jobs.indexOf(jobId), 1);
}
startAllJobs() {
this.logger.log('Starting all jobs');
this.jobs.forEach((job) => {
job.start();
});
}
startJob(jobId: string) {
const job = this.getJob(jobId);
if (job) {
this.logger.log(`Starting job ${jobId}`);
job.start();
} }
} const dashboards = await dbs.findDashboardsByWidgetType(WIDGET_TYPE);
for (let i = 0; i < dashboards.length; i++) {
stopAllJobs() { const dashboard: Dashboard = dashboards[i];
this.logger.log('Stopping all jobs'); for (let j = 0; j < dashboard.data.widgets.length; j++) {
this.jobs.forEach((job) => { const widget = dashboard.data.widgets[j];
job.stop(); if (widget.type === WIDGET_TYPE) {
}); const jobId = `${JOB_PREFIX}_${dashboard.id}_${widget.id}`;
} let cronJob = this.schedulerRegistry.getCronJob(jobId);
if (!cronJob) {
stopJob(jobId: string) { cronJob = new CronJob(
const job = this.getJob(jobId); widget.dataLoaderParams.schedule,
if (job) { async () => {
this.logger.log(`Stopping job ${jobId}`); this.logger.debug(`Cron job ${jobId} started`);
job.stop(); // const report = await dbs.getReport(dashboard.id, widget.id);
this.logger.debug(`Cron job ${jobId} finished`);
// return report;
},
);
this.schedulerRegistry.addCronJob(jobId, cronJob);
}
}
}
} }
this.logger.debug('Auto scan jobs finished');
} }
autoScanJobs() { getDashboardsService(): DashboardsService | null {
throw new Error('Method not implemented.'); if (!this.dashboardsService) {
this.logger.warn('Dashboards service not initialized');
return null;
}
return this.dashboardsService;
}
setDashboardsService(dashboardsService: DashboardsService) {
this.dashboardsService = dashboardsService;
}
private createJobHandler(
jobId: string,
dashboard: Dashboard,
widget: Widget,
): () => void {
return async () => {
this.logger.debug(`Cron job ${jobId} started`);
this.logger.debug(`Cron job ${jobId} finished`);
};
} }
} }