xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

How to automatically run a scheduled task every hour in Node.js All In One

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

  1. 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

  1. 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


特斯拉汽车贷款利率计算器,app 小程序

输入,贷款额,分期数,每月还款额,自动推算出,年利率,符合利率,总利率

https://github.com/web-full-stack/cyclic-express-server

特斯拉 比价爬虫

https://www.cnblogs.com/xgqfrms/p/17349601.html

Web Crawler

https://www.cnblogs.com/xgqfrms/p/17655286.html

/Users/xgqfrms-mm/Documents/github/node-web-framework-all-in-one/000-xyz/crawler/server.js

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

tools

0 */8 * * *

At minute 0 past every 8th hour.

image

https://crontab.guru/#0_/8_**

refs

https://stackoverflow.com/search?q=how+to+run+a+schedule+task+in+Node.js

https://stackoverflow.com/questions/38503557/schedule-task-for-every-4-hours-in-node-js



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-09-02 11:20  xgqfrms  阅读(27)  评论(9编辑  收藏  举报