Stack Exchange
Cron job with child_process not ending child_process of previous run
I have this code:
let { exec } = require("child_process");
const job = new cron.schedule("*/2 * * * *", function () {
        console.log("Cron job Twitter API started");

        exec(
            "node /home/user/Raid/src/sub2/index.js",
            function (error, stdout, stderr) {
                if (error) {
                    console.log(error.stack);
                    console.log("Error code: " + error.code);
                    console.log("Signal received: " + error.signal);
                }
                console.log("Child Process STDOUT: " + stdout);
                console.log("Child Process STDERR: " + stderr);
            }
        );
    });

The problem is, that every 2 minutes the child process is started but not terminated. How can I properly terminate the child_process? The memory of my server is growing very fast and forcing a restart every hour.
I also tried this implementation but with this I did not got an error but the code did not work.
let { exec } = require("child_process");
const job = new cron.schedule("*/2 * * * *", function () {

                if(exec){
                   exec.kill(0);
                }
        console.log("Cron job Twitter API started");

        exec(
            "node /home/user/Raid/src/sub2/index.js",
            function (error, stdout, stderr) {
                if (error) {
                    console.log(error.stack);
                    console.log("Error code: " + error.code);
                    console.log("Signal received: " + error.signal);
                }
                console.log("Child Process STDOUT: " + stdout);
                console.log("Child Process STDERR: " + stderr);
            }
        );
    });

The problem is, that every 2 minutes the child process is started but not terminated. How can I properly terminate the child_process? The memory of my server is growing very fast and forcing a restart every hour.

exec() returns a child object, so you could do it like this:
let childProcess = '0';
    const job = new cron.schedule("*/2 * * * *", function () {
        if (childProcess != '0') {
            childProcess.kill(0);
        }
        console.log("Cron job Twitter API started");

        childProcess = exec(
            "node /home/eliasxxx97/Raid/src/sub2/index.js",
            function (error, stdout, stderr) {
                if (error) {
                    console.log(error.stack);
                    console.log("Error code: " + error.code);
                    console.log("Signal received: " + error.signal);
                }
                console.log("Child Process STDOUT: " + stdout);
                console.log("Child Process STDERR: " + stderr);
            }
        );
    });

