js实现cron
使用 node-cron 库实现定时任务
node-cron 是一个流行的 Node.js 库,用于解析和调度基于 cron 表达式的任务。安装方式如下:
npm install node-cron
示例代码:
const cron = require('node-cron');
cron.schedule('* * * * *', () => {
console.log('每分钟执行一次的任务');
});
cron.schedule('0 0 * * *', () => {
console.log('每天午夜执行的任务');
});
使用原生 JavaScript 实现简单定时器
对于不需要完整 cron 表达式的简单场景,可以使用 setInterval 或 setTimeout:
// 每小时执行一次
setInterval(() => {
console.log('每小时执行的任务');
}, 60 * 60 * 1000);
// 每天特定时间执行
function scheduleDaily(hour, minute, callback) {
const now = new Date();
const target = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
hour,
minute
);
let delay = target - now;
if (delay < 0) {
target.setDate(target.getDate() + 1);
delay = target - now;
}
setTimeout(() => {
callback();
scheduleDaily(hour, minute, callback);
}, delay);
}
scheduleDaily(9, 30, () => {
console.log('每天9:30执行的任务');
});
使用 cron-parser 解析 cron 表达式
如果需要解析 cron 表达式但不执行任务,可以使用 cron-parser:
npm install cron-parser
示例代码:
const parser = require('cron-parser');
const interval = parser.parseExpression('*/5 * * * *');
console.log('下次执行时间:', interval.next().toString());
浏览器环境下的定时任务
浏览器环境中可以使用 Web Workers 实现后台定时任务:
// worker.js
self.onmessage = function(e) {
if (e.data === 'start') {
setInterval(() => {
self.postMessage('tick');
}, 60000); // 每分钟
}
};
// 主线程
const worker = new Worker('worker.js');
worker.onmessage = (e) => {
if (e.data === 'tick') {
console.log('每分钟触发');
}
};
worker.postMessage('start');
高级调度库 bull 或 agenda
对于需要持久化和分布式调度的复杂场景:
npm install bull
示例代码:
const Queue = require('bull');
const queue = new Queue('scheduled-jobs');
queue.add({ foo: 'bar' }, { repeat: { cron: '0 0 * * *' } });
queue.process((job) => {
console.log('处理每日任务', job.data);
});






