'Start and stop NodeJS cron jobs from express API

I have a node file of cronJob.js:

const { exec } = require("child_process");


const cron = require('node-cron');
// Schedule tasks to be run on the server.
cron.schedule('* * * * *', function() {
    console.log("executed")
    exec("node \"C:\\filepath\\callFTP.js\"", (error, stdout, stderr) => {
        if (error) {
            console.log(`error: ${error.message}`);
            return;
        }
        if (stderr) {
            console.log(`stderr: ${stderr}`);
            return;
        }
        console.log(`stdout: ${stdout}`);
    });
  });

Which will basically execute another node file every one minute. I'm building an API to execute this cron job, however, I'm having trouble referencing this cronjob to stop it in a different API call. For example:

app.post('/startSchedulingFTP', function(req, res){
    exec("node \"C:\\filepath\\cronJob.js\"", (error, stdout, stderr) => {
        if (error) {
            console.log(`error: ${error.message}`);
            return;
        }
        if (stderr) {
            console.log(`stderr: ${stderr}`);
            return;
        }
        console.log(`stdout: ${stdout}`);
    });
    res.send("success")
})

This express API will start the cron script, I'm not sure how to get like an ID to reference this cron job to stop it from another API say ```app.post('/stopSchedulingFTP',...)``. Based on this thread, every time a scheduler API is hit, it will create a new instance of a cron job and it suggests that to create a new separate cron job in the same api file. However, as I need to have it separated, the solution is not suitable.

The reason I use the node cron job is that I won't have to worry about the OS of the server in which the application will be installed in.

Any suggestions would be much appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source