简体   繁体   English

在Node.js中运行Cron作业

[英]Run cron job in nodejs

I have this simple cron job function: 我有这个简单的cron作业功能:

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. 在mysql数据库中,我有一个名为“ profsms”的表,该表中有ScheduledTime字段。

If scheduledTime = 18/01/2018 10.00AM 如果ScheduledTime = 18/01/2018 10.00AM

I want to run that cron job by that time dynamically is it possible? 我想在那个时候动态运行该cron作业吗?

You just need to change your time to the cronjob schedule string. 您只需要将时间更改为cronjob时间表字符串即可。

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) 由于您拥有(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. 现在,您只需要将scheduledTime发送到此函数中,这将返回cronjobString。 Use that string to schedule your task. 使用该字符串安排您的任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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