import { CronJob } from 'cron';
class CronUtil {
// jobMap记录了所有的CronJob实例
private static jobMap: Map<string, CronJob> = new Map<string, CronJob>();
/**
* 添加一个定时任务
* @param name 任务名称,用于唯一标识任务
* @param cronTime cron表达式
* @param onTick 定时任务回调函数
* @param onComplete 任务完成回调函数
*/
static addJob(name: string, cronTime: string, onTick: () => void, onComplete?: () => void): void {
if (this.jobMap.has(name)) {
throw new Error(`Cron job with name ${name} already exists`);
}
const job = new CronJob(cronTime, onTick, onComplete, true);
this.jobMap.set(name, job);
}
/**
* 启动指定名称的任务
* @param name 任务名称
*/
static startJob(name: string): void {
const job = this.jobMap.get(name);
if (!job) {
throw new Error(`No cron job found with name ${name}`);
}
if (!job.running) {
job.start();
}
}
/**
* 停止指定名称的任务
* @param name 任务名称
*/
static stopJob(name: string): void {
const job = this.jobMap.get(name);
if (!job) {
throw new Error(`No cron job found with name ${name}`);
}
if (job.running) {
job.stop();
}
}
/**
* 停止所有任务
*/
static stopAllJobs(): void {
for (const [_, job] of this.jobMap) {
job.stop();
}
}
}
export default CronUtil;
使用方式
//任务调度器
CronUtil.addJob('myJob', '*/5 * * * * *', () => {
console.log('Job executed!');
});
CronUtil.startJob('myJob');
此处评论已关闭