I have a class called Scheduler which execute a cron job using the module cron. I have created a function to get the days difference between two dates, that function is working if I call it outside the cron job iteration otherwise it will return
TypeError: this.getDaysDifference is not a function
here's my code:
const CronJob = require('cron').CronJob;
class Scheduler {
async start() {
// HERE WORKING
console.log(this.getDaysDifference(new Date('2020-03-29'), new Date('2020-03-30')));
const job = new CronJob('0 */1 * * * *', async function () {
let messages = await MessageModel.find();
for (const msg of messages) {
// HERE NOT WORKING
console.log(this.getDaysDifference(new Date(), msg.lastScheduler));
}
});
job.start();
}
getDaysDifference = function(start, end) {
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
const utc1 = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate());
const utc2 = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
}
exports.Scheduler = Scheduler;