import fs from 'fs'; import path from 'path'; import scheduler from './scheduler'; import { TaskOptions } from 'node-cron'; interface OneJob { id: string cronTime: string task: Function options: TaskOptions, autoStart: boolean, [key: string]: Function | string | boolean | TaskOptions | undefined } export function defineJob(job: OneJob) { return job; } const jobsDir = path.join(__dirname, 'jobs'); const jobModules: Record = {}; fs.readdirSync(jobsDir).forEach(file => { if (!file.endsWith('Job.ts')) 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: string, hookName: string) { 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: string) => { callHook(id, 'beforeStart'); scheduler.start(id); }, stop: (id: string) => { scheduler.stop(id); callHook(id, 'afterStop'); }, updateCronTime: (id: string, cronTime: string) => scheduler.updateCronTime(id, cronTime), list: () => scheduler.list(), reload: (id: string) => { const job = jobModules[id]; if (job) { scheduler.remove(id); scheduler.add(job.id, job.cronTime, job.task, job.options); } } };