You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.2 KiB
48 lines
1.2 KiB
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);
|
|
}
|
|
}
|
|
};
|
|
|