在 Nodejs Express 应用程序中单击按钮启动/停止 cronjob

Zak*_*Zak 6 javascript cron scheduler node.js express

我一直在开发一个项目,当用户单击前端的按钮时,需要启动和停止 cron 调度程序。基本上,当用户单击按钮时,cron 作业就会启动。单击停止按钮将停止计时器。它是如此简单。

为了实现这一点,我在按钮单击时向 Nodejs/Express 后端发出发布请求,这会触发调度程序的启动/停止功能。端点如下所示:

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)
    }
});
Run Code Online (Sandbox Code Playgroud)

现在,调度程序运行完美,但它不会在单击第二个按钮时停止。它继续运行。我感觉我没有task.start()打电话task.stop()没有在正确的地方打电话。而且我不知道正确的地方在哪里。我实际上是 cronjobs 的新手。

如果有人告诉我我做错了什么,那就太好了。

提前致谢。

Abh*_*kar 4

每次点击都会创建scheduler api一个新的 cron-job 实例,并且您将停止新定义的 cron-job 实例而不是前一个实例

解决方案是将cron-job 定义在路由器的范围之外,这样无论何时点击scheduler api实例都不会改变

像这样:

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)
    }
});
Run Code Online (Sandbox Code Playgroud)