cron 格式
* * * * * * ┬ ┬ ┬ ┬ ┬ ┬ │ │ │ │ │ │ │ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun) │ │ │ │ └───── month (1 - 12) │ │ │ └────────── day of month (1 - 31) │ │ └─────────────── hour (0 - 23) │ └──────────────────── minute (0 - 59) └───────────────────────── second (0 - 59, OPTIONAL)
安装
node -v v16.14.0 pnpm install node-schedule
package.json
{ "type": "module", "dependencies": { "node-schedule": "^2.1.0" } }
示例:每5秒执行一次
import schedule from 'node-schedule' // 秒 分 时 日 月 周 const job = schedule.scheduleJob('*/5 * * * * *', function () { console.log(new Date()); })
运行结果
$ node demo.js 2022-08-15T06:45:05.009Z 2022-08-15T06:45:10.008Z 2022-08-15T06:45:15.004Z 2022-08-15T06:45:20.004Z