Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

613
Views
Iniciar/detener cronjob al hacer clic en el botón en la aplicación Nodejs Express

He estado trabajando en un proyecto que requiere el inicio y la detención del programador cron cuando un usuario hace clic en un botón en la interfaz. Básicamente, cuando un usuario hace clic en un botón, se iniciará el trabajo cron. Y al hacer clic en el botón de parada se detendrá el temporizador. Es tan simple como eso.

Para lograrlo, realizo solicitudes de publicación al backend de Nodejs/Express al hacer clic en el botón que activa la función de inicio/detención del programador. Así es como se ve el punto final:

 const cron = require('node-cron'); router.post('/scheduler', async (req, res) => { // gets the id from the button const id = req.body.id; try{ // finds the scheduler data from the MongoDB const scheduler = await Scheduler.find({ _id: id }); // checks whether there is a scheduler or not if ( !scheduler ) { return res.json({ error: 'No scheduler found.' }); } // creates the cronjob instance with startScheduler const task = cron.schedule('*/10 * * * * *', () => { console.log('test cronjob running every 10secs'); }, { scheduled: false }); // checks if the scheduler is already running or not. If it is then it stops the scheduler if ( scheduler.isRunning ) { // scheduler stopped task.stop(); return res.json({ message: 'Scheduler stopped!' }); } // starts the scheduler task.start(); res.json({ message: 'Scheduler started!' }); }catch(e) { console.log(e) } });

En este momento, el programador funciona perfectamente, pero no se detiene al hacer clic en el segundo botón. Sigue funcionando. Siento que no estoy llamando a task.start() y task.stop() en los lugares correctos donde funcionaría. Y no sé dónde están los lugares correctos. De hecho, soy nuevo en cronjobs.

Sería genial si alguien me dice lo que estoy haciendo mal.

Gracias por adelantado.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Cada vez que presiona la scheduler api se crea una nueva instancia de cron-job y está deteniendo la instancia recién definida de cron-job, no la anterior .

La solución es definir el trabajo cron fuera del alcance del enrutador para que cada vez que presione la scheduler api la instancia no cambie

Me gusta esto:

 const cron = require('node-cron'); // creates the cronjob instance with startScheduler const task = cron.schedule('*/10 * * * * *', () => { console.log('test cronjob running every 10secs'); }, { scheduled: false }); router.post('/scheduler', async (req, res) => { // gets the id from the button const id = req.body.id; try{ // finds the scheduler data from the MongoDB const scheduler = await Scheduler.find({ _id: id }); // checks whether there is a scheduler or not if ( !scheduler ) { return res.json({ error: 'No scheduler found.' }); } // checks if the scheduler is already running or not. If it is then it stops the scheduler if ( scheduler.isRunning ) { // scheduler stopped task.stop(); return res.json({ message: 'Scheduler stopped!' }); } // starts the scheduler task.start(); res.json({ message: 'Scheduler started!' }); }catch(e) { console.log(e) } });
over 4 years ago · Santiago Trujillo Report

0

El problema podría provenir de la línea:

 const task = cron.schedule('*/10 * * * * *', () => {

que, en realidad, crea una nueva tarea y usa un nuevo Programador si lee el código fuente de node-cron: https://github.com/node-cron/node-cron/blob/fbc403930ab3165ffef7d53387a29af92670dfea/src/node-cron. js#L29

 function schedule(expression, func, options) { let task = createTask(expression, func, options); storage.save(task); return task; }

(que, internamente, usa: https://github.com/node-cron/node-cron/blob/fbc403930ab3165ffef7d53387a29af92670dfea/src/scheduled-task.js#L7 :

 let task = new Task(func); let scheduler = new Scheduler(cronExpression, options.timezone, options.recoverMissedExecutions);

Entonces, cuando llames:

 task.stop();

Según tengo entendido, lo que hace es llamar al método "detener" de una tarea nueva , no al método de detener de la tarea que inició la primera vez que hizo clic en el botón.

A juzgar por su código, el problema es que en realidad no está usando su programador mientras usa la tarea.

PD: el módulo también expone una función que le permite recuperar tareas de su almacenamiento: https://github.com/node-cron/node-cron/blob/fbc403930ab3165ffef7d53387a29af92670dfea/src/node-cron.js#L58

Pero como no he encontrado ninguna documentación al respecto, no recomiendo usarlo.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!