用node.js做定时任务

怎样用node.js做定时任务

真的很简单,首先要安装 node-schedule,命令 : npm install node-schedule

使用方法如下:

首先要引入 : 

var schedule = require("node-schedule");  


然后有几种简单的方法供大家选择:

1:确定的时间

var date = new Date(2016,11,29,21,50,0);
schedule.scheduleJob(date, function(){
    console.log("博主很帅");
});  

2:每小时的固定时间

例如:每小时的第30分钟执行

  var rule = new schedule.RecurrenceRule();
  rule.minute = 30;
  var j = schedule.scheduleJob(rule, function(){
    console.log("博主很帅");
  });


3:一个星期中的某些天的某个时刻执行,

例如:周一到周日的22点执行

  var rule = new schedule.RecurrenceRule();
  rule.dayOfWeek = [0, new schedule.Range(1, 6)];
  rule.hour = 22;
  rule.minute = 0;
  var j = schedule.scheduleJob(rule, function(){
    console.log("博主很帅");
  });

 4:每秒执行

  var rule = new schedule.RecurrenceRule();
  var times = [];
  for(var i=1; i<60; i++){
    times.push(i);
  }
  rule.second = times;
  var c=0;
  var j = schedule.scheduleJob(rule, function(){
        c++;
        console.log(c);
  });

还有一种超简单的cron风格定时器:

var schedule = require('node-schedule');
function scheduleCronstyle(){
    schedule.scheduleJob('30 * * * * *', function(){
        console.log('scheduleCronstyle:' + new Date());
    }); 
}
scheduleCronstyle();


* * * * * * * 是什么呢?请看图

*  *  *  *  *  *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │  |
│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
│ │ │ │ └───── month (1 - 12)
│ │ │ └────────── day of month (1 - 31)
│ │ └─────────────── hour (0 - 23)
│ └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)

6个占位符从左到右分别代表:秒、分、时、日、月、周几

'*'表示通配符,匹配任意,当秒是'*'时,表示任意秒数都触发,其它类推

下面可以看看以下传入参数分别代表的意思

每分钟的第30秒触发: '30 * * * * *'

每小时的1分30秒触发 :'30 1 * * * *'

每天的凌晨1点1分30秒触发 :'30 1 1 * * *'

每月的1日1点1分30秒触发 :'30 1 1 1 * *'

2016年的1月1日1点1分30秒触发 :'30 1 1 1 2016 *'

每周1的1点1分30秒触发 :'30 1 1 * * 1'

官网链接: https://www.npmjs.com/package/node-schedule

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值