当前位置:网站首页>nodejs实现定时任务

nodejs实现定时任务

2022-07-22 18:05:00 Fu_Tianshu

本例使用cron来实现定时任务。时间格式支持cron格式和moment格式两种,本例使用moment格式。

依赖

依赖作用链接
cron定时任务对象https://github.com/kelektiv/node-cron
moment设置时间格式https://momentjs.com/
shelljs执行shell命令https://github.com/shelljs/shelljs
pm2守护进程、退出进程https://pm2.keymetrics.io/docs/usage/quick-start/

本例使用pm2对进程进行守护,如下为ecosystem.config.js文件内容。

ecosystem.config.js

module.exports = {
    
    apps : [
        {
    
            name: "timing-task",
            script: "/home/projects/index.js"
        }
    ]
};

index.js

const CronJob = require('cron').CronJob;
const moment = require("moment");
const shell = require("shelljs");
const pm2 = require('pm2');

let job = new CronJob({
    
    cronTime: moment("2021-09-05 18:02:00", "YYYY-MM-DD HH:mm:ss").toDate(),
    onTick: () => {
    
        shell.exec("cp -r /home/projects/timing-task/dir1 /home/projects/timing-task/dir2");
        console.log("运行结束," + moment().format("YYYY-MM-DD HH:mm:ss"));
        pm2.stop("timing-task", () => {
    });
    },
    onComplete: null,
    timeZone: "Asia/Chongqing",
    start: true
});

pm2启动index.js

pm2 start ecosystem.config.js --only timing-task
原网站

版权声明
本文为[Fu_Tianshu]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Fu_Tianshu/article/details/120118630