简体   繁体   中英

can't stop cron job using node-cron

Currently I'm using node-cron package to schedule the task. I can make the task running but I can't make it stop.

My POST body is:

{
command: start/stop/destroy, 
}

The code is:

export const schedule = async (req, res) => {
    const cmd = req.body.command
    const url_taskMap = {}

    // run every midnight GMT+7
    const task = await cron.schedule(process.env.SCHEDULE_TIME, () => {
        console.log('doing task');
    }, {
        scheduled: true,
        timezone: "Asia/Bangkok"
    })

    url_taskMap['url'] = task;
    let my_job = url_taskMap['url'];


    if (cmd === 'start') {
        my_job.start()
        res.status(200).send('Task started!')
    } else if (cmd === 'stop') {
        my_job.stop()
        res.status(200).send('Task stoped!')
    } else {
        my_job.destroy()
        res.status(200).send('Task destroyed!')
    }
}

I follow the answer here https://stackoverflow.com/a/53684854/15088319 but the task still running. I don't know how to make it stop. Can you help me?

I'm not very familiar with node-cron but it looks like there are a couple of problems with this code where the main one is that every request creates a new job, this means that, for example, the first request (cmd: 'start') started a job, then the next request (cmd: 'stop') creates another job and then stops that other job while the first job will keep running...

In order to overcome this problem we need to make sure that only a single instance (at most) of the job will run, and when we want to stop it - we're actually stopping that instance.

This can be achieved by persisting the job that runs, and before running a new job first check if we don't have a job that is already running.

The second problem is that 'stop', if I understand correctly, will stop the scheduling of a task, so for example, if a task was scheduled to run every minute, and task.stop() was called - the task will not be called again in the next minute. This does not mean that your code from a previously running task will stop executing, if your code has an infinite loop, for example, stopping the task will not create more instances of you code running. but the instances that already started to run will run forever. This means that you have the responsibility to make sure you code completes running!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM