问题描述
我使用node-cron每午夜12点运行一个cron作业,正在运行的作业是增加用户表上的一些数据, 现在的问题是作业将运行两次。
例如我想增加 15,12 点后,它会变成 17 而不是 16。
已尽力检测问题,但无法检测。
当我停止 Nodejs 应用程序时,MysqL 数据库不断更新,而 nodejs 应用程序已经关闭 这是正在运行的作业
const CronJob = require('cron').CronJob;
const logger = require("../helpers/logger");
const { updateUser } = require("../helpers/user");
const db = require("../models/db");
const job = new CronJob('* * * * *',async function() {
db.query("UPDATE sponsored_posts SET post_status = 0",(err,data) => {
if (err) logger.debug(err)
});
db.query("DELETE FROM sponsored_posts",data) => {
if (err) logger.debug(err)
});
//EXPIRING USER
db.query("SELECT * FROM all_users WHERE membership_expired > 0",async (err,data) => {
if (data.length > 0) {
//FIlter Through All User
//Deduct While They Havent Expired
await data.map(async user => {
await updateUser({
uid: parseInt(user.uid),membership_expired: user.membership_expired - 1
})
})
}
})
db.query("SELECT * FROM all_users WHERE membership_expired = 0",data) => {
if (data.length > 0) {
//FIlter Through All User
//Set Can Purchase To 1
await data.map(async user => {
await updateUser({
uid: parseInt(user.uid),can_purchase: 1
})
})
}
});
},null,false,"Africa/Lagos");
job.start();
解决方法
如果你使用的是 Linux 系统,你可以使用 crontab 命令来设置你的 cronJob
- 创建一个sh文件
例如,your-cron.sh
// 在那里写你的 cron 脚本执行命令
节点 youscript.js
//或
npm 运行你的脚本
确保您授予执行权限
chmod +x your-cron.sh
- 在 crontab 中设置你的 cron
使用以下命令在 crontab 中设置您的 cron
crontab -e
0 0 * * * /your/absolute/path/your-cron.sh >> /your/absolute/path/logs/your-cron-output.log 2>&1
写命令并保存 使用 crontab -l 确保正确保存
https://crontab.guru/ 是一个帮助您安排 cron 的网站。
0 0 * * * 表示 Cron 每天在 00:00 运行。