Thursday, 8 June 2017

Cron job does not work when populating from config.json file

I am trying to run cron job dynamically based on the config.json In the config.json, I have something like this:

"integrationJobs": [
{
  "desc": "testFunc2",
  "cronExp": "1 * * * * *",
  "fnName": "testFunc2()",
  "module": ""
},
{
  "desc": "testFunc",
  "cronExp": "1 * * * * *",
  "fnName": "testFunc()",
  "module": ""
}]

Then I populate the jobs into an array like this:

var cronJobObjects = config.integrationJobs;   
function initJobs(){  
    var jobs = [];
    for(var i = 0; i < cronJobObjects.length; i++){
        var mName = cronJobObjects[i].module ? cronJobObjects[i].module + '.' : "";
        var fnName = cronJobObjects[i].fnName;
        var fnToExecute = mName + fnName;
        var job = {};
        job = {
            desc: cronJobObjects[i].desc,
            cronExp: cronJobObjects[i].cronExp,
            execute: function() {    
                eval(fnToExecute);
            }
        };
        jobs.push(job);
    }
    console.log('jobs : ' + JSON.stringify(jobs));
    return jobs;
}
module.exports.jobs = initJobs();

Finally, I trigger the jobs:

module.exports.triggerJobs = function () {
    if (integrations.length == 0) {
        setup();
    }
    _.each(integrations, function (integration) {
        if (integration.jobs) {
            _.each(integration.jobs, function (_job) {
                var CronJob = require('cron').CronJob;
                var job = new CronJob({
                    cronTime: _job.cronExp,
                    onTick: function () {
                        console.log('=====> onTick job is ' + JSON.stringify(_job));
                        _job.execute();
                    },
                    start: false,
                    timeZone: _job.timeZone || 'Asia/Singapore'
                });
                job.start();
                console.log('a job has been trigger with exp: ' + _job.cronExp);
            });
        }
    })
}

However, the 2nd job never gets called. Am I missing something at somewhere? The npm package i used is cron https://www.npmjs.com/package/cron

However, if I do setup manually, it works normally

var jobs = [
    {
        "desc": "testFunc",
        "cronExp": "1 * * * * *",
        execute: function () {
            testFunc();
        }
    },
    {
        "desc": "testFunc2",
        "cronExp": "1 * * * * *",
        execute: function () {
            testFunc2();
        }
    }
]
module.exports.jobs = jobs;



via ngunha02

No comments:

Post a Comment