0

I have node application in which I want to run tasks on daily basis. So I want to use node-cron to schedule tasks but not like this:

var cron = require('node-cron');

cron.schedule('* * * * *', function(){
  console.log('running a task every minute');
});

I need some generic solution so that at one place I have just empty body for cron job that takes different functions from a different location. That means in total we have two files, one which has just cron job function handler and other have a list of cron jobs. From where we want to run these jobs we just need require and some basic calling.

Can anyone suggest me this solution?

1 Answers1

1

I got my solution. Using node-cron-job module I have achieved what I wanted. Let me explain in detail:-

First i created new file which contains jobs, lets name it jobs.js :-

// jobs.js 

exports.first_job = {

    on:"* * * * * " //runs every minute
    },
    job: function () {
        console.log("first_job");
    },
    spawn: true             
}

exports.second_job = {

    on: "*/2 * * * * *",    //runs every 2 second 
    job: function () {
        console.log("second_job");
    },
    spawn: false            // If false, the job will not run in a separate process. 
}

Here, we define two jobs name first_job and second_job. We can define as many required.

Finally, we need to call these jobs from any location by these simple steps:-

// main.js 

var cronjob = require('node-cron-job');

cronjob.setJobsPath(__dirname + '/jobs.js');  // Absolute path to the jobs module. 

cronjob.startJob('first_job');  
cronjob.startJob('second_job');

We can call all jobs in a single call like this:-

cronjob.startAllJobs();