78 lines
1.9 KiB
JavaScript
78 lines
1.9 KiB
JavaScript
import cron from 'node-cron';
|
|
import { cron_task_list } from '../config/cron_tasks.js';
|
|
import { get_flow_runner } from './flows/flow_registry.js';
|
|
|
|
const cron_jobs = [];
|
|
const running_task_name_set = new Set();
|
|
|
|
function has_argv_flag(flag_name) {
|
|
const name = String(flag_name || '').trim();
|
|
if (!name) return false;
|
|
return process.argv.includes(name);
|
|
}
|
|
|
|
function should_run_cron_now() {
|
|
return has_argv_flag('--run_cron_now');
|
|
}
|
|
|
|
async function run_cron_task(task) {
|
|
if (!task || !task.type) {
|
|
throw new Error('cron_task 缺少 type');
|
|
}
|
|
|
|
|
|
if (task.type === 'flow') {
|
|
const run_flow = get_flow_runner(task.flow_name);
|
|
await run_flow(task.flow_payload || {});
|
|
return;
|
|
}
|
|
|
|
throw new Error(`cron_task type 不支持: ${task.type}`);
|
|
}
|
|
|
|
async function run_cron_task_with_guard(task_name, task) {
|
|
if (running_task_name_set.has(task_name)) {
|
|
// eslint-disable-next-line no-console
|
|
console.log('[cron] skip (already running)', { name: task_name });
|
|
return;
|
|
}
|
|
|
|
running_task_name_set.add(task_name);
|
|
try {
|
|
await run_cron_task(task);
|
|
} catch (error) {
|
|
console.warn('[cron] error', { task_name, error });
|
|
} finally {
|
|
running_task_name_set.delete(task_name);
|
|
}
|
|
}
|
|
|
|
export async function start_all_cron_tasks() {
|
|
const run_now = should_run_cron_now();
|
|
for (const task of cron_task_list) {
|
|
const task_name = task && task.name ? String(task.name) : 'cron_task';
|
|
|
|
if (run_now) {
|
|
// eslint-disable-next-line no-console
|
|
console.log('[cron] run_now', { task_name });
|
|
await run_cron_task_with_guard(task_name, task);
|
|
}
|
|
else {
|
|
const job = cron.schedule(task.cron_expression, async () => {
|
|
await run_cron_task_with_guard(task_name, task);
|
|
});
|
|
console.log('job', { task_name, });
|
|
cron_jobs.push(job);
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
export function stop_all_cron_tasks() {
|
|
for (const job of cron_jobs) {
|
|
job.stop();
|
|
}
|
|
cron_jobs.length = 0;
|
|
running_task_name_set.clear();
|
|
}
|