nodejs定时任务node-schedule
博客专区 > cyper 的博客 > 博客详情
nodejs定时任务node-schedule
cyper 发表于2年前
nodejs定时任务node-schedule
  • 发表于 2年前
  • 阅读 438
  • 收藏 5
  • 点赞 0
  • 评论 3
摘要: 还是node-schedule好用,later连hello都跑不起来。。。 :)

1:使用npm安装node-schedule模块

npm install node-schedule

(1)每隔5分钟执行一次:

var schedule = require('node-schedule');
var rule = new schedule.RecurrenceRule();
rule.minute = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
var j = schedule.scheduleJob(rule, function () {
    console.log("执行任务:" + new Date());
});

 (2)上午8点到晚上20点每隔5分钟执行一次:
 

var schedule = require('node-schedule');
var rule = new schedule.RecurrenceRule();
rule.hour = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
rule.minute = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
var j = schedule.scheduleJob(rule, function () {
    console.log("执行任务:" + new Date());
});

 

2:以下内容参考:

http://www.codexpedia.com/javascript/nodejs-cron-schedule-examples/

Using the node-schedule to schedule a job to run at a specific time on a specific date. As the first example, the node-schedule module is imported and save it in the variable cron. In the following examle, the require statement will be ommitted and this variable cron will be used.

var cron = require('node-schedule');

/* run the job at 18:55:30 on Dec. 14 2018*/

var date =new Date(2018, 11, 14, 18, 56, 30);

cron.scheduleJob(date,function(){

    console.log(new Date(),"The world is going to end today.");

});

Schedule a recurring job using the RecurrenceRule, example 1.
 

var rule =new cron.RecurrenceRule();

rule.second = 30;

cron.scheduleJob(rule,function(){

    console.log(new Date(),'The 30th second of the minute.');

});

Schedule a recurring job using the RecurrenceRule, example 2.
 

/* This runs at 3:10AM every Friday, Saturday and Sunday. */

var rule2 =new cron.RecurrenceRule();

rule2.dayOfWeek = [5,6,0];

rule2.hour = 3;

rule2.minute = 10;

cron.scheduleJob(rule2,function(){

    console.log('This runs at 3:10AM every Friday, Saturday and Sunday.');

});

Specify the schedule as an object literal.
 

/* This runs at 2:30AM on every Sunday */

cron.scheduleJob({hour: 2, minute: 30, dayOfWeek: 0},function(){

    console.log('This runs at 2:30AM on every Sunday');

});

Specify the schedule in unix cron syntax.
 

/* This runs at the 30th mintue of every hour. */

cron.scheduleJob('30 * * * * *',function(){

    console.log('This runs at the 30th mintue of every hour.');

});

 

标签: node schedule cron
共有 人打赏支持
cyper
粉丝 57
博文 619
码字总数 143041
评论 (3)
cyper
var cron = require('node-schedule');
cron.scheduleJob('*/1 * * * *', function () {
console.log(new Date());
});


每分钟一次。。
cyper
每天18点来一次, 刚测试通过。
var cron = require('node-schedule');
cron.scheduleJob({hour: 18}, function () {
console.log(new Date());
});
cyper
重新排版了一下, 不知道什么时候代码格式乱成一坨
×
cyper
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: