How to automatically run a scheduled task every hour in Node.js All In One
如何在 Node.js 中每间隔一小时自动运行一个
定时任务
引用场景
Node.js 后台爬虫服务,定时爬去指定页面,抓取最新数据,并写入到数据库中;
在同一个 Node.js 部署环境中,没有使用 Linux 的 crontab 权限,只能作为 express.js server 的一个子模块使用,故需要自动定时执行任务
- GitHub schedule
- crontab schedule
solutions
node-schedule
$ npm i node-schedule
https://www.npmjs.com/package/node-schedule
var schedule = require('node-schedule');
var task = schedule.scheduleJob('0 */8 * * *', function () {
console.log('Scheduled Task, every 8 hours');
});
var cron = require('node-schedule');
var rule = new cron.RecurrenceRule();
rule.hour = 8;
rule.minute = 0;
cron.scheduleJob(rule, function(){
console.log(new Date(), 'Every 8 hours');
});
https://github.com/node-schedule/node-schedule
node-cron
$ npm i -S node-cron
https://www.npmjs.com/package/node-cron
var cron = require('node-cron');
cron.schedule('* * * * *', () => {
console.log('running a task every minute');
});
var cron = require('node-cron');
cron.schedule('0 8 * * *', () => {
console.log('Running a job at 08:00 at Asia/Shanghai timezone');
}, {
scheduled: true,
timezone: "Asia/Shanghai"
});
https://github.com/node-cron/node-cron
demos