对于node-schedule执行定时任务,经常使用,但是在使用只执行一次定时任务时,由于用的频率较低(之前一直没用到),就顺手去搜索了一下,结果就是,导致了bug的出现!!!
当你需要在具体的时间执行一次,可以使用new Date来定义一个时间
以下,是官方npm的示例
Date-based Scheduling
Say you very specifically want a function to execute at 5:30am on December 21, 2012. Remember - in JavaScript - 0 - January, 11 - December.
const schedule = require('node-schedule');
const date = new Date(2012, 11, 21, 5, 30, 0);
const job = schedule.scheduleJob(date, function(){
console.log('The world is going to end today.');
});
To use current data in the future you can use binding:
const schedule = require('node-schedule');
const date = new Date(2012, 11, 21, 5, 30, 0);
const x = 'Tada!';
const job = schedule.scheduleJob(date, function(y){
console.log(y);
}.bind(null,x));
x = 'Changing Data';
This will log 'Tada!' when the scheduled Job runs, rather than 'Changing Data', which x changes to immediately after scheduling.
中文解释:
就是说你特别想要一个函数在 2012年12月12日早上5:30执行。
记住在JavaScript中- 0 - 星期一, 11 - 十二月.(意思就是星期数和月份数都是从0开始计数的)
var schedule = require('node-schedule');
var date = new Date(2012, 11, 21, 5, 30, 0);
var j = schedule.scheduleJob(date, function(){
console.log('世界将在今天走向 结束.');
});
要在未来使用当前数据,你可以使用绑定:
var schedule = require('node-schedule');
var date = new Date(2012, 11, 21, 5, 30, 0);
var x = 'Tada!';
var j = schedule.scheduleJob(date, function(y){
console.log(y);
}.bind(null,x));
x = 'Changing Data';
当调度的任务运行时,这个将会打印出’Tada!’,而不是 ‘Changing Data’,
这个x会在调度后立即更改.
此时的new Date中的月份取值范围是1~11,所以
如果你不想因为月份增加代码中的多余操作
:00可以使用如下操作获取date
let date = new Date("2012-12:12 05:30:00")