简体   繁体   中英

Run cron job in nodejs

I have this simple cron job function:

var job = new cronJob('* * * * * *', function () {
  // do some form of stuffs...
 }, function () {
     console.log('DelCron Job finished.');
 }, true, 'Asia/Calcutta');

This will run every second.

My question:

In the mysql database i have one table called "profsms" in this table i have scheduledTime field.

If scheduledTime = 18/01/2018 10.00AM

I want to run that cron job by that time dynamically is it possible?

You just need to change your time to the cronjob schedule string.

Assuming the string to look like this

# ┌────────────── second (optional)
# │ ┌──────────── minute
# │ │ ┌────────── hour
# │ │ │ ┌──────── day of month
# │ │ │ │ ┌────── month
# │ │ │ │ │ ┌──── year
# │ │ │ │ │ │
# │ │ │ │ │ │
# * * * * * *

Since you have (dd/mm/yyyy hour.minute(AM/PM)) (18/01/2018 10.00AM)

const convertTimeToCronJobString = (time) => {
    let retString = '';
    const dmy = time.split(' ')[0];
    const d = dmy.split('/')[0];
    const m = dmy.split('/')[1];
    const y = dmy.split('/')[2];

    const hm = time.split(' ')[1];
    const h = hm.split(';')[0];
    let min = '';
    if (hm.split(';')[1].indexOf('AM') > -1) { // AM
      min = hm.split(';')[1].replace('AM','');
    } else if (hm.split(';')[1].indexOf('AM') > -1) { // PM
      min = hm.split(';')[1].replace('PM','');
      min = String(Number(min) + 12);
    }
    return `0 ${min} ${h} ${d} ${m} ${y}` // you want to start at 0th secound
}

Now you just need to send your scheduledTime into this function and that will return you a cronjobString. Use that string to schedule your task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM