cangku/backend/scripts/jst_reference_sync_scheduler.js

85 lines
2.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const path = require('path');
const cron = require('node-cron');
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
const cloudDb = require('../src/config/cloudDatabase');
const planningDb = require('../src/services/planningDatabase');
const { syncJstReferenceTables } = require('../src/services/planningJstReferenceSync');
const TIMEZONE = process.env.JST_REFERENCE_SYNC_TIMEZONE || 'Asia/Shanghai';
const CRON_EXPRESSION = process.env.JST_REFERENCE_SYNC_CRON || '0 22 * * *';
const CHUNK_SIZE = Number.parseInt(process.env.JST_REFERENCE_SYNC_CHUNK_SIZE || '500', 10) || 500;
const LOOKBACK_MINUTES = Number.parseInt(process.env.JST_REFERENCE_SYNC_LOOKBACK_MINUTES || '10', 10) || 10;
let isRunning = false;
async function closePools() {
await Promise.allSettled([
cloudDb.close(),
planningDb.close(),
]);
}
async function runSync(reason) {
if (isRunning) {
console.log(`[jst-reference-sync-scheduler] 跳过 ${reason},上一轮同步仍在运行`);
return;
}
isRunning = true;
const startedAt = new Date();
console.log(`[jst-reference-sync-scheduler] ${reason} 开始`, startedAt.toISOString());
try {
const result = await syncJstReferenceTables({
table: 'all',
full: false,
chunkSize: CHUNK_SIZE,
lookbackMinutes: LOOKBACK_MINUTES,
onProgress: (payload) => {
console.log(
`[jst-reference-sync-scheduler] ${payload.table} ${payload.fetchedRows}/${payload.totalRows}`
);
},
});
console.log('[jst-reference-sync-scheduler] 同步完成', JSON.stringify(result));
} catch (error) {
console.error('[jst-reference-sync-scheduler] 同步失败:', error);
} finally {
await closePools();
isRunning = false;
console.log(
`[jst-reference-sync-scheduler] ${reason} 结束,用时 ${Date.now() - startedAt.getTime()}ms`
);
}
}
cron.schedule(CRON_EXPRESSION, () => {
runSync('每日22点增量同步');
}, {
timezone: TIMEZONE,
});
setTimeout(() => {
runSync('进程启动增量同步');
}, 1000);
process.on('SIGINT', async () => {
console.log('[jst-reference-sync-scheduler] 收到 SIGINT,准备退出');
await closePools();
process.exit(0);
});
process.on('SIGTERM', async () => {
console.log('[jst-reference-sync-scheduler] 收到 SIGTERM,准备退出');
await closePools();
process.exit(0);
});
console.log(
`[jst-reference-sync-scheduler] 已启动,计划 ${CRON_EXPRESSION},时区 ${TIMEZONE}`
);