I want the cron job to get triggered only when we make a get request, it does for the first time, but if I save it will re-run again.
The code does not run whenever the server starts or restarts but as soon as I hit that specefic endpoint, It will run every time the server re-starts.
startTime = new Date().getTime();
numberOfMinutes = 10;
@Cron(CronExpression.EVERY_MINUTE, {
name: 'myJob',
})
async getParisAirQuality() {
this.logger.verbose(`Getting paris air quality`);
const result = await this.getCityAirQuality({
latitude: '48.856613',
longitude: '2.352222',
});
const airQuality = new this.airQualityModel({
result,
datetime: new Date().toLocaleString(),
});
await airQuality.save();
this.closeJob();
return {
result: airQuality.result,
datetime: new Date().toLocaleString(),
};
}
closeJob() {
const job = this.schedulerRegistry.getCronJob('myJob');
const endTime = this.startTime + 1000 * 60 * Number(this.numberOfMinutes);
if (job.lastDate().getTime() >= endTime) {
job.stop();
}
}