NodeJs实现定时任务的示例代码

穷则独善其身,达则兼善天下。没有梦想的人到达不了成功的彼岸,也就因此而看不到成功的辉煌。没有梦想的人生是失败的,因为他们根本看不到生命的意义。

在项目中有个每天0点执行的函数,本来想用setInterval来实现,但觉得这种需求以后应该还会有,自己写可能拓展性不高。

搜了一下发现了node-schedule这个包。

现在记录一下使用方法

node-schedule没次都是通过新建一个scheduleJob对象来执行具体方法。

时间数值按下表表示

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

使用node-schedule在指定时间执行方法

var schedule = require('node-schedule');
var date = new Date(2017, 11, 16, 16, 43, 0);

var j = schedule.scheduleJob(date, function(){
 console.log('现在时间:',new Date());
});

在2017年12月16日16点43分0秒,打印当时时间

指定时间间隔执行方法

var rule = new schedule.RecurrenceRule();
rule.second = 10;
var j = schedule.scheduleJob(rule, function(){
 console.log('现在时间:',new Date());
});

这是每当秒数为10时打印时间。如果想每隔10秒执行,设置 rule.second =[0,10,20,30,40,50]即可。

rule支持设置的值有second,minute,hour,date,dayOfWeek,month,year

同理:

每秒执行就是rule.second =[0,1,2,3......59]
每分钟0秒执行就是rule.second =0
每小时30分执行就是rule.minute =30;rule.second =0;
每天0点执行就是rule.hour =0;rule.minute =0;rule.second =0;
....
每月1号的10点就是rule.date =1;rule.hour =10;rule.minute =0;rule.second =0;
每周1,3,5的0点和12点就是rule.dayOfWeek =[1,3,5];rule.hour =[0,12];rule.minute =0;rule.second =0;
....

示例

1:确定时间

例如:2014年2月14日,15:40执行

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

  var date = new Date(2014,2,14,15,40,0);

  var j = schedule.scheduleJob(date, function(){

    console.log("执行任务");

  });

取消任务

 j.cancel();

2:每小时的固定时间

例如:每小时的40分钟执行

  var rule = new schedule.RecurrenceRule();

  rule.minute = 40;

  var j = schedule.scheduleJob(rule, function(){

    console.log("执行任务");

  });

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

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

  var rule = new schedule.RecurrenceRule();

  rule.dayOfWeek = [0, new schedule.Range(1, 6)];

  rule.hour = 20;

  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);
  });

以上就是NodeJs实现定时任务的示例代码。吃醋是因为喜欢,生气是因为在乎,发呆是因为想念,伤心是因为不想失去。更多关于NodeJs实现定时任务的示例代码请关注haodaima.com其它相关文章!

您可能有感兴趣的文章
nodejs二进制与Buffer的介绍与使用

nodejs中各种加密算法的实现详解

独立部署小程序基于nodejs的服务器过程详解

NodeJs 模仿SIP话机注册的方法

nodejs实现获取本地文件夹下图片信息功能示例