Nodejs计时器定时执行函数

一、最low的定时器: 每次执行完间隔5s,然后继续执行

(function schedule() {
    setTimeout(do_it, 5000, schedule);
}());
function do_it(callback) {
    var times = new Date();
    console.log(times.getSeconds());
    callback();
};

二、逼格高一点使用插件 node-schedule

  安装:npm install node-schedule

  1、确定时间,例如:2012年11月21日,5:30

var schedule = require('node-schedule');
var date = new Date(2012, 11, 21, 5, 30, 0);
var j = schedule.scheduleJob(date, function(){
    console.log('The world is going to end today.');
});


j.cancel();  //取消预设计划

  2、每小时的固定分钟,例如:每个小时的42分钟

var schedule = require('node-schedule');
var rule = new schedule.RecurrenceRule();
rule.minute = 42; 
var j = schedule.scheduleJob(rule, function(){
    console.log('The answer to life, the universe, and everything!');
});

  3、一个星期中的某些天的某个时刻,例如:每周四,周五,周六,周天的17点

var rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [0, new schedule.Range(4, 6)];
rule.hour = 17;
rule.minute = 0;
var j = schedule.scheduleJob(rule, function(){
    console.log('Today is recognized by Rebecca Black!');
});

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

 

转载于:https://www.cnblogs.com/xbblogs/p/5788907.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值