init
This commit is contained in:
51
middleware/schedule.js
Normal file
51
middleware/schedule.js
Normal file
@@ -0,0 +1,51 @@
|
||||
const node_schedule = require("node-schedule");
|
||||
const logs = require('../tool/logs_proxy');
|
||||
|
||||
class Schedule {
|
||||
// 执行标记,防止并发执行
|
||||
constructor() {
|
||||
this.running_flags = {
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行带锁的任务
|
||||
* @param {string} task_name - 任务名称
|
||||
* @param {Function} task_fn - 任务函数
|
||||
*/
|
||||
async execute_with_lock(task_name, task_fn) {
|
||||
// 如果正在执行,跳过本次执行
|
||||
if (this.running_flags[task_name]) {
|
||||
logs.log(`[定时任务] ${task_name} 正在执行中,跳过本次执行`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 设置执行标记
|
||||
this.running_flags[task_name] = true;
|
||||
|
||||
try {
|
||||
await task_fn();
|
||||
} catch (error) {
|
||||
logs.error(`[定时任务] ${task_name} 执行失败:`, error);
|
||||
} finally {
|
||||
// 清除执行标记
|
||||
this.running_flags[task_name] = false;
|
||||
}
|
||||
}
|
||||
|
||||
async init() {
|
||||
const bizSubscriptionLogic = require("../api/service/biz_subscription_logic");
|
||||
|
||||
node_schedule.scheduleJob("10 0 * * *", async () => {
|
||||
await this.execute_with_lock("biz_subscription_expire", async () => {
|
||||
const n = await bizSubscriptionLogic.expireDueSubscriptions();
|
||||
logs.log(`[定时任务] 订阅到期扫描完成,更新行数: ${n}`);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const schedule = new Schedule();
|
||||
module.exports = schedule;
|
||||
|
||||
Reference in New Issue
Block a user