cangku/backend/src/jobs/planningMayProductSnapshotJob.js

83 lines
2.6 KiB
JavaScript

'use strict';
const cron = require('node-cron');
const planningDatabase = require('../services/planningDatabase');
const {
refreshPlanningMayProductSnapshot,
} = require('../services/planningMayProductDataService');
let running = false;
const JOB_LOCK_WAIT_SECONDS = Math.max(
Number.parseInt(process.env.PLANNING_MAY_PRODUCT_SNAPSHOT_LOCK_WAIT_SECONDS || '1', 10),
0
);
const JOB_ENABLED = String(process.env.PLANNING_MAY_PRODUCT_SNAPSHOT_ENABLED || 'true').toLowerCase() !== 'false';
const JOB_CRON = process.env.PLANNING_MAY_PRODUCT_SNAPSHOT_CRON || '30 8 * * *';
async function withGlobalJobLock(lockKey, trigger, runner) {
const pool = await planningDatabase.getPool();
const connection = await pool.getConnection();
let lockAcquired = false;
try {
const [rows] = await connection.query('SELECT GET_LOCK(?, ?) AS lockStatus', [lockKey, JOB_LOCK_WAIT_SECONDS]);
const lockStatus = rows && rows[0] ? Number(rows[0].lockStatus) : 0;
lockAcquired = lockStatus === 1;
if (!lockAcquired) {
console.log(`[PlanningMayProductSnapshot] global lock not acquired, skip trigger=${trigger}`);
return { success: false, skipped: true, reason: 'global_lock_not_acquired', trigger };
}
return runner();
} finally {
try {
if (lockAcquired) {
await connection.query('DO RELEASE_LOCK(?)', [lockKey]);
}
} finally {
connection.release();
}
}
}
async function runPlanningMayProductSnapshotJob(trigger = 'manual', options = {}) {
if (running) {
console.log(`[PlanningMayProductSnapshot] job is already running, skip trigger=${trigger}`);
return { success: false, skipped: true, reason: 'running', trigger };
}
running = true;
try {
return await withGlobalJobLock('planning_may_product_snapshot_daily', trigger, async () => {
const result = await refreshPlanningMayProductSnapshot({
statDate: options.statDate || null,
chunkSize: options.chunkSize || null,
});
return { ...result, trigger };
});
} finally {
running = false;
}
}
function startPlanningMayProductSnapshotSchedulers() {
if (!JOB_ENABLED) {
console.log('[Scheduler] MAY 商品数据快照任务未启用');
return;
}
cron.schedule(JOB_CRON, () => {
runPlanningMayProductSnapshotJob('daily_schedule').catch((error) => {
console.error('[PlanningMayProductSnapshot] scheduled job failed', error);
});
}, { timezone: 'Asia/Shanghai' });
console.log(`[Scheduler] MAY 商品数据快照任务已注册: ${JOB_CRON} (Asia/Shanghai)`);
}
module.exports = {
startPlanningMayProductSnapshotSchedulers,
runPlanningMayProductSnapshotJob,
};