const EventEmitter = require('events');
const Cron = require('cron');
class CoreCron extends EventEmitter {
constructor(logger) {
super();
this.logger = logger;
this.jobsArray = [];
}
log(message) {
if (this.logger !== null) {
this.logger.log(message);
} else {
console.log(message);
}
}
startCronManager() {
this.CronJob = require('cron').CronJob;
// every minute loggin that cron is still active
this.startJob('heartbeat', '*/5 * * * *', this.logHeartbeart, null);
this.log('CORE | CRON | started cron scheduler');
this.emit('cronStarted');
}
logHeartbeart() {
this.log('CORE | CRON | Heartbeat');
this.emit('cron_every_5_minutes', null);
}
logCronJobRan() {
this.log('CORE | CRON | Job finished execution');
}
/**
* Adds a new CronJob to cron Scheduler
* @param {string} cronDefinition Definition of Job like for cron (e.g. '* * * * *' for run once a minute)
* @param {*} cronFunction function to start if cron starts
* @param {*} onCompleteFunction function to start if cron job has completed (or null)
*/
startJob(title, cronDefinition, cronFunction, onCompleteFunction) {
var job = new this.CronJob(
cronDefinition,
cronFunction,
onCompleteFunction,
true,
'Europe/Berlin',
this
);
job.start();
this.jobsArray.push(job);
this.log('CORE | CRON | Job ' + title + ' started');
}
}
module.exports = CoreCron;