Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cron Job every 10 seconds with Node-Cron

I am using to Node-Cron run a cron job on every 10 seconds. but it seems like there is a issue with node-cron. https://github.com/ncb000gt/node-cron#cron-ranges

i made a request at 04:28:34 but the script started at 4:28:40(should start at 04:28:44)

i made a request at 04:48:58 but the script started at 04:49:00 (should start at 04:49:08)

i made a request at 05:03:45 but the script started at 05:03:50 (should start at 04:49:08)

below is my code to execute this task.

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));

});
like image 644
dev1234 Avatar asked May 18 '15 05:05

dev1234


People also ask

How do I run a cron job every second?

How do I run a cron job every second? Running a cron every second is not possible but you can run it every second with alternate way. You can use sleep command, to do this you have to create a scripts a define sleep command for example every X seconds.

How do I run a cron job every 5 seconds?

Cron only allows for a minimum of one minute. What you could do is write a shell script with an infinite loop that runs your task, and then sleeps for 5 seconds. That way your task would be run more or less every 5 seconds, depending on how long the task itself takes.


1 Answers

This worked for me -

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

Hope this helps someone.

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

like image 80
Ishaan Avatar answered Sep 21 '22 12:09

Ishaan