nodejs定时任务
示例代码
js
// 定时任务:每日凌晨 0:00 自动生成卡密压缩包并上传
const cron = require('node-cron');
const { doGenerateKamiZip } = require('./configApi');
console.log('[Cron] 定时任务已注册,每天 00:00 (Asia/Shanghai) 自动生成卡密');
cron.schedule('0 0 * * *', async () => {
console.log('[Cron] ========== 开始定时生成卡密 ==========', new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }));
try {
const result = await doGenerateKamiZip(db);
console.log('[Cron] 生成卡密结果:', JSON.stringify(result));
} catch (err) {
console.error('[Cron] 生成卡密异常:', err.message, err.stack);
}
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});Node-Cron 定时任务表达式大全
基础语法说明
* * * * * *
│ │ │ │ │ │
│ │ │ │ │ └── 星期 (0-7, 0和7都代表周日)
│ │ │ │ └──── 月份 (1-12)
│ │ │ └────── 日期 (1-31)
│ │ └──────── 小时 (0-23)
│ └────────── 分钟 (0-59)
└──────────── 秒 (可选,0-59)一、按固定间隔执行
1. 每秒执行一次
javascript
const cron = require('node-cron');
// 每秒执行
cron.schedule('* * * * * *', () => {
console.log('每秒执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});2. 每5秒执行一次
javascript
cron.schedule('*/5 * * * * *', () => {
console.log('每5秒执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});3. 每10秒执行一次
javascript
cron.schedule('*/10 * * * * *', () => {
console.log('每10秒执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});4. 每30秒执行一次
javascript
cron.schedule('*/30 * * * * *', () => {
console.log('每30秒执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});5. 每分钟执行一次
javascript
cron.schedule('* * * * *', () => {
console.log('每分钟执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});6. 每5分钟执行一次
javascript
cron.schedule('*/5 * * * *', () => {
console.log('每5分钟执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});7. 每15分钟执行一次
javascript
cron.schedule('*/15 * * * *', () => {
console.log('每15分钟执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});8. 每30分钟执行一次
javascript
cron.schedule('*/30 * * * *', () => {
console.log('每30分钟执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});9. 每小时执行一次
javascript
cron.schedule('0 * * * *', () => {
console.log('每小时执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});10. 每2小时执行一次
javascript
cron.schedule('0 */2 * * *', () => {
console.log('每2小时执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});11. 每6小时执行一次
javascript
cron.schedule('0 */6 * * *', () => {
console.log('每6小时执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});12. 每12小时执行一次
javascript
cron.schedule('0 */12 * * *', () => {
console.log('每12小时执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});二、每天特定时间执行
13. 每天凌晨 00:00 执行
javascript
cron.schedule('0 0 * * *', () => {
console.log('每天00:00执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});14. 每天早上 08:00 执行
javascript
cron.schedule('0 8 * * *', () => {
console.log('每天早上08:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});15. 每天中午 12:00 执行
javascript
cron.schedule('0 12 * * *', () => {
console.log('每天中午12:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});16. 每天下午 18:00 执行
javascript
cron.schedule('0 18 * * *', () => {
console.log('每天下午18:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});17. 每天晚上 22:30 执行
javascript
cron.schedule('30 22 * * *', () => {
console.log('每天晚上22:30执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});18. 每天多个时间点执行(如 08:00、12:00、18:00)
javascript
cron.schedule('0 8,12,18 * * *', () => {
console.log('每天08:00、12:00、18:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});19. 每隔3天执行一次
javascript
cron.schedule('0 0 */3 * *', () => {
console.log('每隔3天执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});三、每周执行
20. 每周一执行一次
javascript
cron.schedule('0 0 * * 1', () => {
console.log('每周一00:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});21. 每周一至周五执行
javascript
cron.schedule('0 9 * * 1-5', () => {
console.log('每周一到周五09:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});22. 每周六、周日执行
javascript
cron.schedule('0 10 * * 0,6', () => {
console.log('每周六、周日10:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});23. 每周三和周五执行
javascript
cron.schedule('0 0 * * 3,5', () => {
console.log('每周三和周五00:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});24. 每周工作日凌晨备份
javascript
cron.schedule('0 2 * * 1-5', () => {
console.log('工作日凌晨02:00执行备份', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});25. 每周一早上09:30执行
javascript
cron.schedule('30 9 * * 1', () => {
console.log('每周一09:30执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});四、每月执行
26. 每月1号执行
javascript
cron.schedule('0 0 1 * *', () => {
console.log('每月1号00:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});27. 每月15号执行
javascript
cron.schedule('0 0 15 * *', () => {
console.log('每月15号00:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});28. 每月最后一天执行
javascript
cron.schedule('0 0 28-31 * *', () => {
// 注意:需要额外判断是否为当月最后一天
const now = new Date();
const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
if (now.getDate() === lastDay) {
console.log('每月最后一天执行', new Date().toLocaleString());
}
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});29. 每月1号和15号执行
javascript
cron.schedule('0 0 1,15 * *', () => {
console.log('每月1号和15号00:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});30. 每月10号上午10:30执行
javascript
cron.schedule('30 10 10 * *', () => {
console.log('每月10号10:30执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});31. 每两个月执行一次(奇数月1号)
javascript
cron.schedule('0 0 1 1,3,5,7,9,11 *', () => {
console.log('奇数月1号00:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});五、每年执行
32. 每年1月1日执行(年初)
javascript
cron.schedule('0 0 1 1 *', () => {
console.log('每年1月1日00:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});33. 每年12月31日执行(年末)
javascript
cron.schedule('0 0 31 12 *', () => {
console.log('每年12月31日00:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});34. 每年6月1日执行
javascript
cron.schedule('0 0 1 6 *', () => {
console.log('每年6月1日00:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});35. 每两年执行一次
javascript
let yearCount = 0;
cron.schedule('0 0 1 1 *', () => {
yearCount++;
if (yearCount % 2 === 1) { // 奇数年执行
console.log('每两年执行一次(奇数年)', new Date().toLocaleString());
}
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});六、指定具体日期时间执行
36. 指定日期执行(2026-05-09 12:00:00)
javascript
const scheduleSpecificDate = (targetDateStr, callback) => {
const targetDate = new Date(targetDateStr);
const now = new Date();
const delay = targetDate.getTime() - now.getTime();
if (delay > 0) {
setTimeout(() => {
callback();
console.log(`指定时间 ${targetDateStr} 执行完成`);
}, delay);
console.log(`已设置定时器,将在 ${targetDateStr} 执行`);
} else {
console.log(`目标时间 ${targetDateStr} 已过期`);
}
};
// 使用示例
scheduleSpecificDate('2026-05-09 12:00:00', () => {
console.log('指定日期 2026-05-09 12:00:00 执行');
});37. 使用 node-cron 模拟指定日期执行(结合一次性任务)
javascript
const { CronJob } = require('cron'); // 需要使用 cron 包
// 安装: npm install cron
const job = new CronJob(
'0 0 12 9 5 *', // 5月9日12:00
() => {
console.log('指定日期 5月9日12:00 执行', new Date().toLocaleString());
job.stop(); // 执行后停止
},
null,
true,
'Asia/Shanghai'
);38. 多组指定日期执行
javascript
const specificDates = [
'2026-01-01 00:00:00',
'2026-05-01 00:00:00',
'2026-10-01 00:00:00',
'2026-12-25 00:00:00'
];
specificDates.forEach(dateStr => {
const targetDate = new Date(dateStr);
const now = new Date();
const delay = targetDate.getTime() - now.getTime();
if (delay > 0) {
setTimeout(() => {
console.log(`节假日任务执行: ${dateStr}`, new Date().toLocaleString());
}, delay);
}
});七、组合复杂场景
39. 工作日每小时执行一次
javascript
cron.schedule('0 * * * 1-5', () => {
console.log('工作日每小时执行一次', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});40. 非工作日的凌晨执行
javascript
cron.schedule('0 3 * * 0,6', () => {
console.log('周末凌晨03:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});41. 每月第一个周一执行
javascript
cron.schedule('0 0 * * 1', () => {
const now = new Date();
const dayOfMonth = now.getDate();
if (dayOfMonth <= 7) {
console.log('每月第一个周一执行', new Date().toLocaleString());
}
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});42. 每季度第一天执行
javascript
cron.schedule('0 0 1 1,4,7,10 *', () => {
console.log('每季度第一天00:00执行', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});43. 夏令时调整兼容写法
javascript
cron.schedule('0 3 * * *', () => {
// 凌晨3点执行,避开夏令时变更时间
console.log('凌晨03:00执行(避开夏令时)', new Date().toLocaleString());
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});八、实用工具函数
44. 通用定时任务启动器
javascript
/**
* 通用定时任务管理器
*/
class CronManager {
constructor() {
this.jobs = [];
}
/**
* 添加定时任务
* @param {string} expression - cron表达式
* @param {Function} task - 任务函数
* @param {Object} options - 配置选项
*/
addJob(expression, task, options = {}) {
const job = cron.schedule(expression, async () => {
try {
console.log(`[${new Date().toLocaleString()}] 执行任务: ${expression}`);
await task();
} catch (error) {
console.error(`[${new Date().toLocaleString()}] 任务失败:`, error.message);
}
}, {
scheduled: true,
timezone: options.timezone || 'Asia/Shanghai',
...options
});
this.jobs.push({ expression, job });
return job;
}
/** 停止所有任务 */
stopAll() {
this.jobs.forEach(({ expression, job }) => {
job.stop();
console.log(`任务已停止: ${expression}`);
});
this.jobs = [];
}
/** 获取所有任务列表 */
getJobs() {
return this.jobs.map(({ expression }) => expression);
}
}
// 使用示例
const manager = new CronManager();
manager.addJob('0 0 * * *', async () => {
console.log('每日备份任务执行');
// 实际业务逻辑
});
manager.addJob('0 9 * * 1-5', async () => {
console.log('工作日数据同步');
});
manager.addJob('0 0 1 * *', async () => {
console.log('月度报表生成');
});45. 一次性定时任务封装
javascript
/**
* 一次性定时任务(指定未来某个时间点执行)
* @param {Date|string} targetTime - 目标时间
* @param {Function} callback - 回调函数
* @returns {Promise}
*/
function runOnceAt(targetTime, callback) {
return new Promise((resolve, reject) => {
const target = typeof targetTime === 'string' ? new Date(targetTime) : targetTime;
const now = new Date();
const delay = target.getTime() - now.getTime();
if (delay <= 0) {
reject(new Error(`目标时间 ${target.toLocaleString()} 已过期`));
return;
}
console.log(`一次性任务已注册,将在 ${target.toLocaleString()} 执行(剩余 ${Math.round(delay / 1000)} 秒)`);
setTimeout(async () => {
try {
const result = await callback();
resolve(result);
} catch (error) {
reject(error);
}
}, delay);
});
}
// 使用示例
runOnceAt('2026-12-31 23:59:59', async () => {
console.log('年终总结任务执行');
return { success: true, time: new Date().toISOString() };
}).then(result => {
console.log('任务执行成功:', result);
}).catch(err => {
console.error('任务执行失败:', err.message);
});九、完整示例:每日卡密生成任务
javascript
const cron = require('node-cron');
const { doGenerateKamiZip } = require('./routes/novelDownloader/pages/configApi');
// 数据库连接(假设已有)
const db = require('./database');
console.log('[Cron] ========================================');
console.log('[Cron] 定时任务系统初始化');
console.log('[Cron] 当前时间:', new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }));
console.log('[Cron] ========================================');
// 1. 每日凌晨 00:00 生成卡密压缩包
cron.schedule('0 0 * * *', async () => {
console.log('[Cron] ========== 开始每日卡密生成 ==========');
console.log('[Cron] 执行时间:', new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }));
try {
const result = await doGenerateKamiZip(db);
console.log('[Cron] 卡密生成成功:', JSON.stringify(result));
} catch (err) {
console.error('[Cron] 卡密生成失败:', err.message);
console.error('[Cron] 错误堆栈:', err.stack);
}
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});
// 2. 每周一凌晨 01:00 生成周报
cron.schedule('0 1 * * 1', async () => {
console.log('[Cron] ========== 开始生成周报 ==========');
// 周报生成逻辑
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});
// 3. 每月1号凌晨 02:00 生成月报
cron.schedule('0 2 1 * *', async () => {
console.log('[Cron] ========== 开始生成月报 ==========');
// 月报生成逻辑
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});
// 4. 每年1月1日凌晨 03:00 生成年报
cron.schedule('0 3 1 1 *', async () => {
console.log('[Cron] ========== 开始生成年报 ==========');
// 年报生成逻辑
}, {
scheduled: true,
timezone: 'Asia/Shanghai'
});
console.log('[Cron] 所有定时任务已注册完成');
console.log('[Cron] 等待执行中...');十、常用 Cron 表达式速查表
| 用途 | Cron 表达式 | 说明 |
|---|---|---|
| 每秒 | * * * * * * | 每秒执行一次 |
| 每10秒 | */10 * * * * * | 每10秒执行一次 |
| 每分钟 | * * * * * | 每分钟执行一次 |
| 每5分钟 | */5 * * * * | 每5分钟执行一次 |
| 每15分钟 | */15 * * * * | 每15分钟执行一次 |
| 每30分钟 | */30 * * * * | 每30分钟执行一次 |
| 每小时 | 0 * * * * | 每小时整点执行 |
| 每2小时 | 0 */2 * * * | 每2小时整点执行 |
| 每天00:00 | 0 0 * * * | 每天凌晨执行 |
| 每天08:00 | 0 8 * * * | 每天早上8点执行 |
| 每天12:00 | 0 12 * * * | 每天中午12点执行 |
| 每周一 | 0 0 * * 1 | 每周一凌晨执行 |
| 每周一至周五 | 0 9 * * 1-5 | 工作日早上9点执行 |
| 每月1号 | 0 0 1 * * | 每月1号凌晨执行 |
| 每月15号 | 0 0 15 * * | 每月15号凌晨执行 |
| 每年1月1日 | 0 0 1 1 * | 每年元旦执行 |
| 每年12月31日 | 0 0 31 12 * | 每年年末执行 |
注意事项:
- 使用
timezone: 'Asia/Shanghai'确保北京时间执行- 长时间运行的任务建议加
async/await处理异步逻辑- 关键任务要添加 try-catch 错误处理
- 一次性定时任务建议用
setTimeout替代 cron- 生产环境建议配合日志系统记录任务执行状态
