全屏浏览
缩小浏览
回到页首

fs项目---->cron框架的学习(一)

  Cron是一种允许您按计划执行某些内容的工具。这通常使用cron语法来完成。我们允许您在计划作业触发时执行函数。我们还允许您使用子进程执行javascript进程外部的作业。此外,这个库超出了基本的cron语法,允许您提供日期对象。这将用作回调的触发器。Cron语法仍然是一种可接受的CronTime格式。虽然这里支持的Cron模式在标准Unix格式上扩展为支持秒数,但如果不使用它,则默认为0,并与Unix行为相匹配。


一、简要的介绍

安装: npm install cron

cron支持的格式:

Asterisk. E.g. *  (每unit)
Ranges. E.g. 1-3,5(第1,2,3unit)
Steps. E.g. */2   (每2unit)

cron值的范围,这个可能与标准的有一些差别。

  • Seconds: 0-59
  • Minutes: 0-59
  • Hours: 0-23
  • Day of Month: 1-31
  • Months: 0-11 (Jan-Dec)
  • Day of Week: 0-6 (Sun-Sat)

二、cron的api使用

这里面我们先介绍一下cron里面的api,再详细的说明一下cron的语法所代表的含义。我们以一个简单的例子开头,如下:

const CronJob = require('cron').CronJob;
const job = new CronJob('*/1 * * * * *', function () {
    console.log(`You will see this message every second ${new Date()}`);
});
console.log('After job instantiation');
job.start();

打印的结果如下所示,每秒打印一次。

After job instantiation
You will see this message every second Sat Sep 15 2018 13:07:29 GMT+0800 (China Standard Time)
You will see this message every second Sat Sep 15 2018 13:07:30 GMT+0800 (China Standard Time)
You will see this message every second Sat Sep 15 2018 13:07:31 GMT+0800 (China Standard Time)
You will see this message every second Sat Sep 15 2018 13:07:32 GMT+0800 (China Standard Time)
.......

现在我们看一下CronJob对象里面的参数:

constructor(cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean);

关于对象参数的说明如下:

  • cronTime - [REQUIRED] - The time to fire off your job. This can be in the form of cron syntax or a JS Date object.
  • onTick - [REQUIRED] - The function to fire at the specified time. If an onComplete callback was provided, onTick will receive it as an argument. onTick may call onComplete when it has finished its work.
  • onComplete - [OPTIONAL] - A function that will fire when the job is stopped with job.stop(), and may also be called by onTick at the end of each run.
  • start - [OPTIONAL] - Specifies whether to start the job just before exiting the constructor. By default this is set to false. If left at default you will need to call job.start() in order to start the job (assuming job is the variable you set the cronjob to). This does not immediately fire your onTick function, it just gives you more control over the behavior of your jobs.
  • timeZone - [OPTIONAL] - Specify the timezone for the execution. This will modify the actual time relative to your timezone. If the timezone is invalid, an error is thrown. You can check all timezones available at Moment Timezone Website. Probably don't use both. timeZone and utcOffset together or weird things may happen.
  • context - [OPTIONAL] - The context within which to execute the onTick method. This defaults to the cronjob itself allowing you to call this.stop(). However, if you change this you'll have access to the functions and values within your context object.
  • runOnInit - [OPTIONAL] - This will immediately fire your onTick function as soon as the requisite initialization has happened. This option is set to false by default for backwards compatibility.
  • utcOffset - [OPTIONAL] - This allows you to specify the offset of your timezone rather than using the timeZone param. Probably don't use both timeZone and utcOffset together or weird things may happen.
  • unrefTimeout - [OPTIONAL] - If you have code that keeps the event loop running and want to stop the node process when that finishes regardless of the state of your cronjob, you can do so making use of this parameter. This is off by default and cron will run as if it needs to control the event loop. For more information take a look at timers#timers_timeout_unref from the NodeJS docs
  • cronTime为Date类型,而且设置了start=true(不用调用job.start()方法就启动了cron)和runOnInit=true(启动就执行了onTick函数)
const CronJob = require('cron').CronJob;
const now = new Date();
const param = {
    cronTime: new Date(now.getTime() + 1000 * 5),
    onTick: function() {
        console.log(`You will see this message after 5 second again ${new Date()}`);
    },
    start: true,
    runOnInit: true
};
const job = new CronJob(param);
console.log('job status ' + job.running);

运行的结果如下:

You will see this message after 5 second again Sat Sep 15 2018 13:22:28 GMT+0800 (China Standard Time)
job status true
You will see this message after 5 second again Sat Sep 15 2018 13:22:33 GMT+0800 (China Standard Time)
  • cronTime为cron格式,而且设置了onComplete函数,stop之后得到lastdate数值。
const CronJob = require('cron').CronJob;
const param = {
    cronTime: '*/2 * * * * *',
    onTick: function() {
        console.log(`You will see this message every two second again ${new Date()}`);
    },
    onComplete: function() {
        console.log(`job status = ${job.running} and date = ${new Date()}`);
    }
};
const job = new CronJob(param);
console.log(`job status = ${job.running}`);
job.start();
setTimeout(() => {
    job.stop();
    console.log(`last execute date is ${job.lastDate()}`)
}, 1000 * 10);

运行的一次结果如下:

job status = undefined
You will see this message every two second again Sat Sep 15 2018 13:34:00 GMT+0800 (China Standard Time)
You will see this message every two second again Sat Sep 15 2018 13:34:02 GMT+0800 (China Standard Time)
You will see this message every two second again Sat Sep 15 2018 13:34:04 GMT+0800 (China Standard Time)
You will see this message every two second again Sat Sep 15 2018 13:34:06 GMT+0800 (China Standard Time)
You will see this message every two second again Sat Sep 15 2018 13:34:08 GMT+0800 (China Standard Time)
job status = false and date = Sat Sep 15 2018 13:34:09 GMT+0800 (China Standard Time)
last execute date is Sat Sep 15 2018 13:34:08 GMT+0800 (China Standard Time)
  • 在onTick中使用context(默认是CronJob对象),可以调用stop方法、start、running等
const CronJob = require('cron').CronJob;
const now = new Date(new Date().getTime() + 1000 * 5);
const param = {
    cronTime: '* * * * * *',
    onTick: function() {
        console.log(`${new Date()}`);
        if(now < new Date()) {
            this.context.stop();
        }
    }
};
const job = new CronJob(param);
console.log(`now is ${new Date()}`);
job.start();

运行的结果如下:

now is Sat Sep 15 2018 14:43:00 GMT+0800 (China Standard Time)
Sat Sep 15 2018 14:43:01 GMT+0800 (China Standard Time)
Sat Sep 15 2018 14:43:02 GMT+0800 (China Standard Time)
Sat Sep 15 2018 14:43:03 GMT+0800 (China Standard Time)
Sat Sep 15 2018 14:43:04 GMT+0800 (China Standard Time)
Sat Sep 15 2018 14:43:05 GMT+0800 (China Standard Time)
Sat Sep 15 2018 14:43:06 GMT+0800 (China Standard Time)

三、关于cron格式的例子

我们先举一个完整的例子,后面都是在这基础上做的修改。完整例子代码如下:

  • 2 * * * * *:每分钟中的第二秒执行一次
const CronJob = require('cron').CronJob;
const param = {
    cronTime: '2 * * * * *',
    onTick: function() {
        console.log(`${new Date()} and context is ${this.context.running}`);
    }
};
const job = new CronJob(param);
console.log(`now is ${new Date()}`);
job.start();

运行的结果如下:

now is Sat Sep 15 2018 14:29:07 GMT+0800 (China Standard Time)
Sat Sep 15 2018 14:30:02 GMT+0800 (China Standard Time) and context is true
Sat Sep 15 2018 14:31:02 GMT+0800 (China Standard Time) and context is true
Sat Sep 15 2018 14:32:02 GMT+0800 (China Standard Time) and context is true
......
  • 2 34-37 * * * *:每小时中的第34分2秒、第35分2秒、第36分2秒、第37分2秒执行一次
now is Sat Sep 15 2018 14:34:50 GMT+0800 (China Standard Time)
Sat Sep 15 2018 14:35:02 GMT+0800 (China Standard Time) and context is true
Sat Sep 15 2018 14:36:02 GMT+0800 (China Standard Time) and context is true
Sat Sep 15 2018 14:37:02 GMT+0800 (China Standard Time) and context is true
......
  • 1-30/6 22-23 14-15 * * *:每天的14点或者15点中的22分或者23分中的第1秒、7秒、13秒、19秒、25秒执行一次
now is Sat Sep 15 2018 14:22:58 GMT+0800 (China Standard Time)
Sat Sep 15 2018 14:23:01 GMT+0800 (China Standard Time) and context is true
Sat Sep 15 2018 14:23:07 GMT+0800 (China Standard Time) and context is true
Sat Sep 15 2018 14:23:13 GMT+0800 (China Standard Time) and context is true
Sat Sep 15 2018 14:23:19 GMT+0800 (China Standard Time) and context is true
Sat Sep 15 2018 14:23:25 GMT+0800 (China Standard Time) and context is true
Sat Sep 15 2018 14:23:25 GMT+0800 (China Standard Time) and context is true 
Sat Sep 15 2018 14:23:25 GMT+0800 (China Standard Time) and context is true
........
  • 1-30/6,33 * * * * *:每分中的第1秒、7秒、13秒、19秒、25秒、33秒执行一次
now is Sat Sep 15 2018 14:54:18 GMT+0800 (China Standard Time)
Sat Sep 15 2018 14:54:19 GMT+0800 (China Standard Time) and context is true
Sat Sep 15 2018 14:54:25 GMT+0800 (China Standard Time) and context is true
Sat Sep 15 2018 14:54:33 GMT+0800 (China Standard Time) and context is true
Sat Sep 15 2018 14:55:01 GMT+0800 (China Standard Time) and context is true
Sat Sep 15 2018 14:55:07 GMT+0800 (China Standard Time) and context is true
......
  • */5 * * * * *:每5秒执行一次
now is Sun Sep 16 2018 20:14:51 GMT+0800 (China Standard Time)
Sun Sep 16 2018 20:14:55 GMT+0800 (China Standard Time) and context is true
Sun Sep 16 2018 20:15:00 GMT+0800 (China Standard Time) and context is true
Sun Sep 16 2018 20:15:05 GMT+0800 (China Standard Time) and context is true
...... 

posted @ 2018-09-15 15:02  huhx  阅读(529)  评论(0编辑  收藏  举报