I have a json configuration file that hold a list of default jobs to schedule in my nodeJS app. The purposer is to schedule (with node-schedule) some functions of my module from this file to manually define its interval.
The problem is that the json file store the function name (job.name
below) as string ans I need to pass a function to schedule.scheduleJob
.
I tried with this[job.name]
and module[job.name]
but it is the same.
Thanks in advance
// ../conf/service
{
"scheduler": {
"defaultJobs": [
{ "name": "jobOne", "schedule": "*/1 * * * * *" }, // each second
{ "name": "jobTwo", "schedule": "*/3* * * * *" } // every 3 seconds
]
}
}
const schedule = require('node-schedule');
const conf = require('../conf/service').scheduler;
let count=0;
function jobOne() {
console.log(`jobOne n°${count++}`);
}
let count1=0;
function jobTwo() {
console.log(`jobTwo n°${count1++}`);
}
conf.defaultJobs.forEach(job => {
schedule.scheduleJob(job.schedule, job.name); // call jobOne and jobTwo
});
You can do the trick by storing your functions inside an object:
const schedule = require('node-schedule');
const conf = require('../conf/service').scheduler;
let count=0;
function jobOne() {
console.log(`jobOne n°${count++}`);
}
let count1=0;
function jobTwo() {
console.log(`jobTwo n°${count1++}`);
}
const jobs = {
jobOne,
jobTwo
}
conf.defaultJobs.forEach(job => {
schedule.scheduleJob(job.schedule, jobs[job.name]); // call jobOne and jobTwo
});