Schedule and cancel task in Node.JS (Node-cron, cron or Schedule)

Asked

Viewed 599 times

1

I created a simple server with two routes, one to start a periodic service /job/start and another to cancel it /job/stop.

Here’s the code:

// framework
const express = require('express');
const app = express();

// router
const router = express.Router();
router.get('/job/:order', (req, res) => {

    // função a ser executada periodicamente
    const periodicFoo = () => console.log('__PERIODIC_FOO__');

    // configuração do cronograma
    const cron = require('node-cron');
    cron.schedule('periodic-foo', '*/3 * * * * *', periodicFoo);   
    const job = cron.getTasks['periodic-foo'];

    // inicia ou cancela o cronograma
    switch (req.params.order) {
        case ('start'):
            job.start();
            res.send('Job Start');
        break;
        case ('stop'):
            job.stop();
            res.send('Job Stop');
        break;
        default:
            res.send('Job no order');
        break;
    }
});
app.use(router);

// running
app.listen(3001, () => console.log('Server running!'));

Dependencies of package.json for testing purposes:

  "dependencies": {
    "cron": "^1.8.2",
    "express": "^4.17.1",
    "node-cron": "^2.0.3",
    "node-schedule": "^1.3.2"
  }

As you can see, I’ve tested several libraries node-cron, cron and node-schedule.

But all without success.

Look at this article in Stackoverflow: How to stop a Node cron job.

It’s nice, but it didn’t work either.

So that’s it.

I want to create a server with a route to boot a job that would run indefinitely & periodically and another to cancel that task.

How can I do that?

Note: Creating the task is easy. The hard part is to open a new tab in the browser (i.e., a new instance of the Node server) that corresponds to the same job as the other instance in order to select and cancel it.

1 answer

1

Hello, I know the topic has been open for a long time, but I went through something similar and found a solution that can help you.

I used the lib Node-Schedule and I did the following:

const schedule = require('node-schedule');

//scheduleList vai ser a lista de processos que você criou utilizando a lib
const scheduleList = schedule.scheduledJobs;
//processName vai ser o nome do processo que você vai passar na hora que criar um processo utilizando a lib
if (scheduleList['processName'] != undefined) {
    //Nesse caso, caso ele ache o nome do processo na lista vamos utilizar o nome dele para cancela-lo.
    scheduleList.processName.cancel();
}
//Aqui vou criar um processo
const currentDate = new Date();
//scheduleDate é a data qual o processo vai rodar, neste caso apos 1 minuto da data em que esse script foi chamado
const scheduleDate = new Date(currentDate.getTime() + 1 * 60000);

schedule.scheduleJob('processName', scheduleDate, function () {
      console.log('Acabamos de criar um novo processo com o nome de processName');
    });

In this example you can see how to create a process using lib Node-Schedule, how to list processes created through it and how to cancel a process using the name you were given.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.