import fs from 'fs'; import path from 'path'; import scheduler from 'utils/scheduler.js'; const jobsDir = __dirname; const jobModules = {}; fs.readdirSync(jobsDir).forEach(file => { if (file === 'index.js' || !file.endsWith('Job.js')) return; const jobModule = require(path.join(jobsDir, file)); const job = jobModule.default || jobModule; if (job && job.id && job.cronTime && typeof job.task === 'function') { jobModules[job.id] = job; scheduler.add(job.id, job.cronTime, job.task, job.options); if (job.autoStart) scheduler.start(job.id); } }); function callHook(id, hookName) { const job = jobModules[id]; if (job && typeof job[hookName] === 'function') { try { job[hookName](); } catch (e) { console.error(`[Job:${id}] ${hookName} 执行异常:`, e); } } } export default { start: id => { callHook(id, 'beforeStart'); scheduler.start(id); }, stop: id => { scheduler.stop(id); callHook(id, 'afterStop'); }, updateCronTime: (id, cronTime) => scheduler.updateCronTime(id, cronTime), list: () => scheduler.list(), reload: id => { const job = jobModules[id]; if (job) { scheduler.remove(id); scheduler.add(job.id, job.cronTime, job.task, job.options); } } };