0

I'm using node-cron for scheduling in my express backend, here is the example. I set my scheduling configuration in index.js, and I've develop the function that will execute by cron in training.js

index.js:

const training = require('./training');

const DAILY = 'DAILY';
const HOURLY = 'HOURLY';

function getCronSchedule(when){
    switch (when) {
        case DAILY : return "55 22 * * *";
        case HOURLY : return "10 * * * *";
    }
}
function initJob()
{
    training.initJob(getCronSchedule(HOURLY));
    training.initJob(getCronSchedule(DAILY));
}

module.exports={
    initJob
}

training.js:

function initJob(when)
{
    console.log('This is daily scheduling');
    console.log('This is hourly scheduling');
}

module.exports={
    initJob
}

Currently, the:

This is daily scheduling
This is hourly scheduling

will be printed two times every day, because it printed on daily and hourly scheduling.

What I need is each of them printed once for each day.

This is daily scheduling printed on daily cron and,

This is hourly scheduling printed on hourly cron.

How do I can make it? I dont know how to make the condition, because what I got from param just the cron schedule.

Blackjack
  • 1,016
  • 1
  • 20
  • 51
  • Your `initJob` function doesn't contain any logic that separates daily from hourly as so it will always print the 2 console.log statements. – VladNeacsu Oct 18 '19 at 06:45

2 Answers2

0

From the node-cron examples your code should be something like this:

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

cron.schedule('55 22 * * *', () => {
  console.log('This is daily scheduling');
});

cron.schedule('55 22 * * *', () => {
  console.log('This is hourly scheduling');
});
VladNeacsu
  • 1,268
  • 16
  • 33
0

try the below code, Hope this will help:

index.js

const training = require('./training');

const DAILY = 'DAILY';
const HOURLY = 'HOURLY';

function getCronSchedule(when){
    switch (when) {
        case DAILY : return "2 * * * *";
        case HOURLY : return "* * * * *";
    }
}
function initJob()
{
    training.initJob(getCronSchedule(HOURLY),HOURLY);
    training.initJob(getCronSchedule(DAILY),DAILY);
}

module.exports={
    initJob
}

initJob()

training.js

var cron = require('node-cron');
const DAILY = 'DAILY';
const HOURLY = 'HOURLY';

function initJob(when, name)
{   
  switch(name){
    case DAILY : cron.schedule(when, () => {
    console.log('This is daily scheduling');
  });
    case HOURLY : cron.schedule(when, () => {
    console.log('This is hourly scheduling');
  });

  }

}

module.exports={
    initJob
}

Hope this will help.

Shishir Naresh
  • 743
  • 4
  • 10