使用 Node-Cron 每 10 秒执行一次 Cron 作业

Posted

技术标签:

【中文标题】使用 Node-Cron 每 10 秒执行一次 Cron 作业【英文标题】:Cron Job every 10 seconds with Node-Cron 【发布时间】:2015-07-29 12:18:04 【问题描述】:

我使用 Node-Cron 每 10 秒运行一次 cron 作业。但似乎node-cron存在问题。 https://github.com/ncb000gt/node-cron#cron-ranges

我在04:28:34 提出了请求,但脚本从4:28:40 开始(应该从04:28:44 开始)

我在04:48:58 提出了请求,但脚本从04:49:00 开始(应该从04:49:08 开始)

我在05:03:45 提出了请求,但脚本从05:03:50 开始(应该从04:49:08 开始)

以下是我执行此任务的代码。

router.post('/secret', function (req, res) 
    console.log('Post request!');
    console.log('Start At:' + getUTCDateTime());

    function getUTCDateTime() 

        var date = new Date();
        var dateUTC = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
        var hour = dateUTC.getHours();
        hour = (hour < 10 ? "0" : "") + hour;
        var min = dateUTC.getMinutes();
        min = (min < 10 ? "0" : "") + min;
        var sec = dateUTC.getSeconds();
        sec = (sec < 10 ? "0" : "") + sec;
        var year = dateUTC.getFullYear();
        var month = dateUTC.getMonth() + 1;
        month = (month < 10 ? "0" : "") + month;
        var day = dateUTC.getDate();
        day = (day < 10 ? "0" : "") + day;
        return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec; // format: 2015-04-10 11:40:50

    

    function getEndDateTime(startAt, callback) 

        var date = new Date(startAt);
        date.setSeconds(date.getSeconds() + parseInt(callback));
        var sec = date.getSeconds();
        sec = (sec < 10 ? "0" : "") + sec;
        var hour = date.getHours();
        hour = (hour < 10 ? "0" : "") + hour;
        var min = date.getMinutes();
        min = (min < 10 ? "0" : "") + min;
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        month = (month < 10 ? "0" : "") + month;
        var day = date.getDate();
        day = (day < 10 ? "0" : "") + day;
        return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec; // format: 2015-04-10 11:40:50

    

    function getStartDateTime(startAt, callback) 

        var date = new Date(startAt);
        date.setSeconds(date.getSeconds() - parseInt(callback));
        var sec = date.getSeconds();
        sec = (sec < 10 ? "0" : "") + sec;
        var hour = date.getHours();
        hour = (hour < 10 ? "0" : "") + hour;
        var min = date.getMinutes();
        min = (min < 10 ? "0" : "") + min;
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        month = (month < 10 ? "0" : "") + month;
        var day = date.getDate();
        day = (day < 10 ? "0" : "") + day;
        return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec; // format: 2015-04-10 11:40:50

    

    function callBackUrl(url, data)
        var request = require('request');

        request.post(
            url,
            form: data: data,
            function (error, response, body) 
                if (!error && response.statusCode == 200) 
                    console.log(body)
                
            
        );

    

    var startAt = req.body.startAt;
    var callback = req.body.callback;
    var endAt = req.body.endAt; //2015-05-15 11:23:50
    var data = req.body.data;
    if (callback == "" || endAt == "" || data == "")
        res.end('Params cannot be empty: ' + JSON.stringify(req.body));

    if (getUTCDateTime() >= endAt)
        res.end('Param "endAt" is invalid: ' + JSON.stringify(req.body));

    var jsonObject = JSON.parse(data); //to get the JSON object of the string


    var callbackUrl1 = 'http://qa.www.com/index.php/api/default/test/id/1';
    var callbackUrl2 = 'http://qa.www.com/index.php/api/default/test/id/2';
    //cronStartAt = '0 */' + callback + ' * * * *'; // only every 1 minute
    cronStartAt = '*/' + callback + ' * * * * *'; // only every 1 minute
    var nowCount = 0;
    var CronJob = require('cron').CronJob;
    var cron = new CronJob(cronStartAt, function () 
        nowCount++;
        var tmpStartAt = getStartDateTime(getUTCDateTime(), callback);
        var tmpEndAt = getUTCDateTime();
        //var tmpStartAt = getUTCDateTime();
        //var tmpEndAt = getEndDateTime(tmpStartAt, callback);
        //console.log(tmpStartAt + ' ' + tmpEndAt);
        jsonObject.startAt = tmpStartAt;
        jsonObject.endAt = tmpEndAt;
        data = JSON.stringify(jsonObject);

        callBackUrl(callbackUrl1, data);
        if (getUTCDateTime() >= endAt) 
            cron.stop();
            console.log('stopped at: ' + getUTCDateTime());
            console.log('now count: ' + nowCount);
        
    , function () 
        /* This function is executed when the job stops */
        // on crone stop another http call with submitted post data
        callBackUrl(callbackUrl2, data);
    , true, 'America/Los_Angeles');

    cron.start();
    console.log("Post body: %j", req.body);
    res.end('Body: ' + JSON.stringify(req.body));

);

【问题讨论】:

callback 中的值是多少?还有你如何衡量作业的执行时间? Can a cron job run every 'x' seconds的可能重复 【参考方案1】:

这对我有用 -

    cron.schedule("*/10 * * * * *", function() 
      console.log("running a task every 10 second");
    );

希望这对某人有所帮助。

参考 - https://support.acquia.com/hc/en-us/articles/360004224494-Cron-time-string-format

【讨论】:

以上是关于使用 Node-Cron 每 10 秒执行一次 Cron 作业的主要内容,如果未能解决你的问题,请参考以下文章

CronJob只执行一次

使用 Node-Cron 每 45 分钟运行一次 Cron 作业

linux每10秒执行一次

lua脚本延迟10秒怎么写

在 ASP.NET Web API 中创建一个线程每 X 秒执行一次特定代码

如何每 20 秒执行一次 bash 脚本? ,好用睡眠和循环?