57 lines
2.0 KiB
TypeScript
57 lines
2.0 KiB
TypeScript
import { Injectable, Logger } from '@nestjs/common';
|
|
import { SchedulerRegistry } from '@nestjs/schedule';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { isError } from '@stdlib/assert';
|
|
import { CronJob, CronTime } from 'cron';
|
|
import { Repository } from 'typeorm';
|
|
import { EBITEMP_API_DATASOURCE } from '../database/connections/ebitemp-api/database.constants';
|
|
import { TipiJobsEntity } from '../database/connections/ebitemp-api/entities/tipi_jobs.entity';
|
|
|
|
@Injectable()
|
|
export class SchedulerService {
|
|
private readonly logger = new Logger(SchedulerService.name);
|
|
|
|
private static readonly TIME_ZONE = 'Europe/Rome';
|
|
|
|
constructor(
|
|
private readonly schedulerRegistry: SchedulerRegistry,
|
|
@InjectRepository(TipiJobsEntity, EBITEMP_API_DATASOURCE)
|
|
private readonly tipiJobsRepository: Repository<TipiJobsEntity>
|
|
) {}
|
|
|
|
async onApplicationBootstrap() {
|
|
try {
|
|
const jobs = this.schedulerRegistry.getCronJobs();
|
|
const jobTypes = await this.tipiJobsRepository.find();
|
|
|
|
for (const [jobName, job] of jobs) {
|
|
this.rescheduleJobAccordingToJobType(jobTypes, jobName, job);
|
|
}
|
|
} catch (err) {
|
|
if (!isError(err)) throw err;
|
|
this.logger.error(err.message);
|
|
this.logger.warn(`Error while retrieving scheduled jobs on database. Skipping jobs.`);
|
|
}
|
|
}
|
|
|
|
private rescheduleJobAccordingToJobType(jobTypes: TipiJobsEntity[], jobName: string, job: CronJob) {
|
|
const jobType = jobTypes.find((jobType) => jobType.nome == jobName);
|
|
|
|
if (!jobType) {
|
|
this.logger.warn(`Job type for job '${jobName}' not found on database. Skipping job.`);
|
|
this.schedulerRegistry.deleteCronJob(jobName);
|
|
return;
|
|
}
|
|
|
|
const jobTime = new CronTime(jobType.patternCron, SchedulerService.TIME_ZONE);
|
|
job.setTime(jobTime);
|
|
job.start();
|
|
|
|
this.logger.log(
|
|
`Job type id '${jobType.id}' found for job '${jobName}' [isActive: ${jobType.flagAttivo}, cronPattern: ${
|
|
jobType.patternCron
|
|
}]. Upcoming date => ${job.nextDate()}`
|
|
);
|
|
}
|
|
}
|