宝塔部署Nodejs定时任务

项目背景:

一个nuxt服务端渲染项目,用到了mongodb数据库,后端接口使用的node的express框架

需要定时备份mongodb数据库

编写定时任务代码 

nodejs 代码放在 nuxt 项目的 server 目录下,在 server 目录下有一个 command 目录,里面存放定时任务,一个任务一个 js 文件,注意 command 目录权限 777

nuxt 根目录下有一个 ecosystem.config.js ,这个是 pm2 需要执行的文件


贴出 ecosystem.config.js 代码

const GLOBAL = require('./server/config/global.config')

module.exports = {
  apps: [
    {
      name: 'nuxt站名称',
      script: 'server/index.js',
      env: {
        COMMON_VARIABLE: 'true',
      },
      env_production: {
        NODE_ENV: 'production',
      },
    },
    {
      name: '定时任务1名称',
      script: 'server/command/backup.js',
      env: {
        COMMON_VARIABLE: 'true',
      },
      env_production: {
        NODE_ENV: 'production',
      },
    },
    {
      name: '定时任务2名称',
      script: 'server/command/2.js',
      env: {
        COMMON_VARIABLE: 'true',
      },
      env_production: {
        NODE_ENV: 'production',
      },
    },
  ],
  deploy: {
    production: {
      user: 'root',
      ref: 'origin/master',
      host: GLOBAL.pm2.host,
      repo: GLOBAL.pm2.repo,
      path: GLOBAL.pm2.path,
      'post-deploy': 'npm install && npm run build && pm2 reload ecosystem.config.js --env production',
    },
  },
}

 贴出定时任务代码

const schedule = require('node-schedule');//引入定时任务模块
const process = require('child_process');//引入cmd模块
const fs = require('fs');//引入fs模块
const path = require('path');//引入path

const host = "127.0.0.1:27017";//数据库地址及端口
const database = "test";//备份的数据库名称
const backupPath = '/www/backup/mongodb/test';//备份路径如
const cmd = `mongodump -h ${host} -d ${database} -o ${backupPath}`;//mongodb备份命令
// 秒(0-59) 分(0-59) 时(0-23) 天(0-31) 月(0-12) 周(0-7)
const time = "0 0 1 * * *";//定时时间 每天凌晨1点
// 以下时间打印时使用,亦可省略
const now = new Date();
const Y = now.getFullYear();//获取年
const M = (now.getMonth()+1) > 9 ? (now.getMonth()+1) : '0' + (now.getMonth()+1);//获取月
const D = now.getDate() > 9 ? now.getDate() : '0' + now.getDate();//获取日
const h = now.getHours() > 9 ? now.getHours() : '0' + now.getHours();//获取时
const m = now.getMinutes() > 9 ? now.getMinutes() : '0' + now.getMinutes();//获取分
const s = now.getSeconds() > 9 ? now.getSeconds() : '0' + now.getSeconds();//获取秒

// 定义方法
function backupDatabase(){
    console.log(`==========>开始备份${database}数据库,${Y}-${M}-${D} ${h}:${m}:${s}`)
    schedule.scheduleJob(time, function(){  //每天凌晨1时整
        process.exec(cmd, async function(error, stdout, stderr) {  //在cmd中执行上方定义的命令
            if (error) {
                console.log('Error:'+ error); //错误
            } else if (stderr.lenght > 0) {
                console.log('Stderr:'+stderr.toString())  //标准性错误
            } else {
                //成功之后写入日志
                let year = (new Date()).getFullYear();//获取年
                let month = ((new Date()).getMonth()+1) > 9 ? ((new Date()).getMonth()+1) : '0' + ((new Date()).getMonth()+1);//获取月
                let date = (new Date()).getDate() > 9 ? (new Date()).getDate() : '0' + (new Date()).getDate();//获取日
                let hour = (new Date()).getHours() > 9 ? (new Date()).getHours() : '0' + (new Date()).getHours();//获取时
                let minute = (new Date()).getMinutes() > 9 ? (new Date()).getMinutes() : '0' + (new Date()).getMinutes();//获取分
                let seconds = (new Date()).getSeconds() > 9 ? (new Date()).getSeconds() : '0' + (new Date()).getSeconds();//获取秒
                let str = `${year}-${month}-${date} ${hour}:${minute}:${seconds} 备份`;
                // 写下日志文件
                await fs.writeFile(path.join(backupPath,'.log'),`\n${str}`, {flag:'a+'},(err) =>{ //第一个参数 为存储路径 如:/www/backup/mongodb/test/.log  我这里存储在备份数据库目录下
                    if(err){
                        console.log(err)
                    }
                })
                console.log(`==========>备份${database}数据库完成,${year}-${month}-${date} ${hour}:${minute}:${seconds}`)
            }
        });
    }); 
}

backupDatabase();

 部署定时任务

打开 pm2 配置

 

 提交之后你的定时任务就成功部署在 linux 服务器上了

注意:

这里运行用户一定要改为 root ,否则会没有权限去备份


 当然了,如果你仅仅只需要部署 nodejs 的定时任务,你 pm2 添加启动文件的时候,只需要选择你的 js 文件即可,总而言之,nodejs 服务必须使用 pm2 来部署(如果你有别的方式,那么另当别论)


 广告:(提供学习机会)

       前端交流学习群:1063233592

       PHP学习交流群:901759097

       前后端学习交流微信群:加我微信,填写验证消息(前后端),拉你进群

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端薛小帅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值