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.