节点调度运行任务太多次

Node schedule runs task too many times

我为自己构建了一个随机报价生成器,它每天发送一封包含报价的电子邮件。 为了构建它,我使用了 node-schedule 包。

我指定它每天在 16:00 它应该执行一个函数:

schedule.scheduleJob("* * 16 * * *", () => {
  scheduler();
  console.log("hey");
});

但事实证明它做了很多次,而不仅仅是一次。

有什么问题?

完整代码如下:

const express = require("express");
const app = express();
const nodemailer = require("nodemailer");
const fetch = require("node-fetch");
const schedule = require("node-schedule");

app.get("*", (req, res) => {
  res.send("<h1>Hello, wolrd!</h1>");
});
schedule.scheduleJob("* * 16 * * *", () => {
  scheduler();
  console.log("hey");
});
function scheduler() {
  let qoute = {};
  fetch("https://api.quotable.io/random", {
    method: "GET"
  })
    .then(data => {
      return data.json();
    })
    .then(info => {
      qoute.qoute = info.content;
      qoute.author = info.author;

      mailer(qoute);
    })
    .catch(error => console.error(error));
}

// async..await is not allowed in global scope, must use a wrapper
async function mailer(qoute) {
  // Generate test SMTP service account from ethereal.email
  // Only needed if you don't have a real mail account for testing
  // let testAccount = await nodemailer.createTestAccount();

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: "mail.google.com",
    port:123,
    secure: false, // true for 465, false for other ports
    auth: {
      user: "robot@gmail.com", // generated ethereal user
      pass: "123456" // generated ethereal password
    }
  });

  // send mail with defined transport object
  let info = await transporter.sendMail(
    {
      from: '"John doe " <hello@mail.com>', // sender address
      to: "abc@gmail.com", // list of receivers
      subject: ` Here's your daily qoute`, // Subject line

      html: `
<b>${qoute.qoute} <span>-${qoute.author}</span>
      ` 
    },
    function(err, info) {
      if (err) console.log(err);
      else console.log(info);
    }
  );
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`listening on port: ${port}`));

因此,对于结果,我希望这个 scheduler() 函数应该只 运行 一次。

谢谢。

您还需要传递分和秒(可选)。 “* * 16 * * *”表示从16:00到17:00每分每秒运行。 所以你需要像这样更正时间

schedule.scheduleJob("0 16 * * *", () => {
  scheduler();
  console.log("hey");
});