gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:39:14 29 4
gpt4 key购买 nike

我一直在做一个项目,当用户单击前端的按钮时,它需要启动和停止 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)
}
});
现在调度程序运行完美,但它不会在第二个按钮单击时停止。它继续运行。我觉得我没有调用 task.start()task.stop()在正确的地方,它会工作。而且我不知道正确的地方在哪里。我实际上是 cronjobs 的新手。
如果有人告诉我我做错了什么,那就太好了。
提前致谢。

最佳答案

每次点击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)
}
});

关于javascript - 在 Nodejs Express 应用程序中单击按钮时启动/停止 cronjob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66987333/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com