Node.js中做定时任务
用node-cron
这个库:https://github.com/kelektiv/node-cron
例子:
//import {CronJob} from 'cron';
const CronJob = require('cron').CronJob;
const job = new CronJob(
'* * * * * *', //cron time
function(){
console.log('You will see this message every second');
},
null, //onComplete
true, //start
'Asia/Shanghai' //timeZone
);
job.start();
注:用import {CronJob} from 'cron'
的时候报错SyntaxError: Cannot use import statement outside a module
Node.js用的是CommonJS
的标准,而import是ES6
的标准,所以这里要用require
, 或者把.js
扩展名改为.mjs
,这样即可以兼容ES6,用import ... from 就不会报错了。
执行:node cron.js
node cron.js
You will see this message every second
You will see this message every second
You will see this message every second
You will see this message every second
......