在Node.js服务器上调度间隔24小时的多个cron任务的方案咨询
解决方案
核心思路:放弃依赖服务运行时长的延时注册逻辑,改用公历日期差值取模的规则匹配任务,只要服务器系统时间准确,无论服务是否重启、何时重启,任务运行时序都不会错乱。
实现方案
方案一:统一日调度 + 任务匹配(推荐,逻辑最简洁)
只注册一个每天12点触发的cron任务,通过日期差值模3的结果判断当天要执行的任务,代码示例如下:
import cron from 'node-cron' // 固定基准日期,替换为你第一次运行job1的公历日期,确定后不要修改 const BASE_DATE = new Date('2024-01-01') // 计算两个日期的天数差 const getDayDiff = (date1, date2) => { const oneDay = 24 * 3600 * 1000 // 对齐时分秒,避免时区/时间点偏差导致的天数计算错误 const d1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) const d2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()) return Math.round((d1 - d2) / oneDay) } // 每天12点触发调度 cron.schedule('0 0 12 * * *', () => { const dayDiff = getDayDiff(new Date(), BASE_DATE) const mod = dayDiff % 3 switch(mod) { case 0: console.log('run job 1') // 此处写job1的执行逻辑 break case 1: console.log('run job 2') // 此处写job2的执行逻辑 break case 2: console.log('run job 3') // 此处写job3的执行逻辑 break } })
方案二:三个任务独立调度,各自加匹配判断
如果需要三个任务完全独立注册,也可以给每个任务单独加判断规则,代码示例如下:
import cron from 'node-cron' const BASE_DATE = new Date('2024-01-01') const getDayDiff = (date1, date2) => { const oneDay = 24 * 3600 * 1000 const d1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) const d2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()) return Math.round((d1 - d2) / oneDay) } // job1 调度 cron.schedule('0 0 12 * * *', () => { if (getDayDiff(new Date(), BASE_DATE) % 3 === 0) { console.log('run job 1') } }) // job2 调度 cron.schedule('0 0 12 * * *', () => { if (getDayDiff(new Date(), BASE_DATE) % 3 === 1) { console.log('run job 2') } }) // job3 调度 cron.schedule('0 0 12 * * *', () => { if (getDayDiff(new Date(), BASE_DATE) % 3 === 2) { console.log('run job 3') } })
注意事项
- 基准日期确定后不要修改,否则会打乱已有的运行时序
- 确保服务器系统时间与时区设置准确,避免日期计算出现偏差
内容的提问来源于stack exchange,提问作者mandmeier
相关产品推荐
相关产品推荐

