定时任务实现

实现定时任务和后台作业

提示词

请实现定时任务系统:

任务类型:
1. 定时执行(如每天凌晨2点)
2. 间隔执行(如每5分钟)
3. 延迟执行(如30分钟后)
4. Cron表达式

使用:[node-cron/Bull/AGV等]

要求:
1. 任务定义和注册
2. 任务调度
3. 失败重试
4. 任务状态监控
5. 并发控制
6. 任务日志
7. 分布式锁(多实例部署)

示例输出

使用Bull + Redis:

const Queue = require('bull');

// 创建队列
const reportQueue = new Queue('reports', process.env.REDIS_URL);

// 定义任务处理
reportQueue.process('daily-report', async (job) => {
  job.progress(0);
  const data = await generateReport();
  job.progress(50);
  await sendEmail(data);
  job.progress(100);
  return data;
});

// 添加定时任务(每天凌晨2点)
const dailyJob = await reportQueue.add(
  'daily-report',
  { type: 'daily' },
  {
    repeat: { cron: '0 2 * * *' },
    attempts: 3,
    backoff: { type: 'exponential', delay: 5000 }
  }
);

// 事件监听
reportQueue.on('completed', (job, result) => {
  console.log(`任务${job.id}完成`);
});

reportQueue.on('failed', (job, err) => {
  console.error(`任务${job.id}失败:`, err);
});
0

评论 0

更多

登录后可点赞、收藏、评论和举报。

还没有评论,先发起一个具体问题。