Search code examples
javascriptnode.jscronnode-cron

Is there any way to get milliseconds in CronJobs?


I want to trigger a JavaScript function every 500ms using node cron jobs, though I couldn't find a way to make the cron execute any lower than a 1 second interval.

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

Is there any way to run a function every 500ms using node cron jobs?


Solution

  • Setting a cron job to execute that frequently is not possible, and for good reason - a task executing that frequently shouldn't be done using a cron.

    Instead, you can use Timers with Node.js:

    function myFunc(arg) {
        console.log("Argument received: " + arg);
    }
    
    setTimeout(myFunc, 500, "some message"); // Executes every 500ms.
    

    Timers can also be instantiated into a variable:

    const timeoutObject = setTimeout(() => {
        console.log("I will print every 500ms!");
    }, 500);
    
    clearTimeout(timeoutObject);