Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

javascript - Node cron schedule not running on pm2

I have question to ask about running cron schedule using pm2 on remote server. I have tested on my localhost and it works using the cron schedule but when I upload this to the remote server and running with pm2 it does not work. The file that contains the cron schedule is called "index.js" and when I test it on my localhost I do "node index.js". On remote server I run the index.js file as "pm2 start ./index.js".

Also, I did pm2 log to see any specific error about the cron but I dont see anything. And I tried running -> pm2 start ./index.js --cron "0 */1 * * * *" but this does not work as well.

I will post my index.js code below

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var cors = require("cors");
var sms = require("./smsMessage");
var path = require("path");
const sql = require("mssql");

const cron = require("node-cron");
let shell = require("shelljs");
var nodemailer = require("nodemailer");

const corsOptions = {
  origin: true,
  credentials: true,
};

app.use(cors(corsOptions));
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));

//DB CONNECTION
const config = {
  user: "*****",
  password: "*****",
  server: "*****",
  database: "*****",
  encrypt: false,
  parseJSON: true,
  options: {
    enableArithAbort: true,
  },
};

//API FOR TWILIO
const accountSid = process.env.accountSid;
const authToken = process.env.authToken;
const client = require("twilio")(accountSid, authToken);

//0 */45 * * * *
//0 */1 * * * *
cron.schedule("0 */1 * * * *", function () {
  sql.on("error", (err) => {
    console.log("Something Went Wrong");
  });

  //EMAIL FOR "*****"
  let transporter = nodemailer.createTransport({
    host: "*****",
    port: "*****",
    secure: false,
    auth: {
      user: "*****",
      pass: "*****",
    },
    tls: {
      rejectUnauthorized: false,
    },
  });

  sql
    .connect(config)
    .then((pool) => {
      var qry =
        " SELECT " +
        "        * " +
        "        FROM( " +
        "SELECT toEmail,idClaim, sentDate, phone, DATEDIFF(DAY, CURRENT_TIMESTAMP, sentDate) as DAYINTERVAL, content  FROM EMAIL_LOG_CREATE EM INNER JOIN users U ON EM.idClaim = U.idCustomer  " +
        "        WHERE isActive = '0'  " +
        "                ) a WHERE DAYINTERVAL = '-3' ";

      return pool.request().query(qry);
    })
    .then((result) => {
      // THIS LOOP WILL SEND OUT THE MESSAGE
      var tel = "";
      var SMSMessage = "";
      for (var i = 0; i < result.recordsets[0].length; i++) {
        tel = "+1" + result.recordset[i].phone;
        SMSMessage =
          "Please create a password for your new account by clicking this link. http://localhost:8877/new/register?email=" +
          result.recordset[i].toEmail +
          "&id=" +
          result.recordset[i].idClaim;

        // SMSMessage =
        //   "Please create a password for your new account by clicking this link. http://"*****"/new/register?email=" +
        //   result.recordset[i].toEmail +
        //   "&id=" +
        //   result.recordset[i].idClaim;

        client.messages
          .create({
            body: SMSMessage,
            from: "*****",
            to: tel,
          })
          .then((message) => console.log(message.sid));
      }

      // THIS FOR LOOP WILL SEND OUT THE EMAIL
      for (var i = 0; i < result.recordsets[0].length; i++) {
        var mailOptions = {
          from: '""*****""<"*****">;',
          to: result.recordset[i].toEmail,
          subject: "NEW USER",
          html: result.recordset[i].content,
        };
        transporter.sendMail(mailOptions, function (error, info) {
          if (error) {
            console.log(error);
          } else {
            console.log("Email sent: " + info.response);
          }
        });
      }
    })
    .catch((err) => {
      console.log(err);
    });
});

app.use(function (req, res, next) {
  const allowedOrigins = ["http://"*****"", "http://localhost:3000"];
  const origin = req.headers.origin;
  if (allowedOrigins.includes(origin)) {
    res.setHeader("Access-Control-Allow-Origin", origin);
  } else {
    res.header("Access-Control-Allow-Origin", "*");
  }
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  next();
});

app.use("/", sms);

app.listen(5000, function (req, res) {
  console.log("Server listening at port no. 5000");
});

module.exports = app;

(UPDATE) Okay so I think the error might be coming from somewhere else. I have Checked the terminal and it returned this error. I will post the image below this again.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...