javascript - Node 调度运行任务太多次

标签 javascript node.js express node-schedule

我为自己构建了一个随机报价生成器,它每天发送一封包含报价的电子邮件。 为了构建它,我使用了 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");
});

关于javascript - Node 调度运行任务太多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58343125/

相关文章:

node.js - 无法从 Controller 调用 Sequelize 模型自定义函数

javascript - jquery - 可以使文本消失但不能使隐藏文本可见

javascript - 在 Web 应用程序中存储大量 session 数据的最佳方式是什么?

node.js - 如何在node js中使用多个内容发送邮件?

node.js - Express js,mongodb : "ReferenceError: db is not defined" when db is mentioned outside post function

javascript - postman 回复 : Could not get any response from server

javascript - 它在 body 上使用 div。它不使用get

javascript - 对象值未定义

node.js - NodeJs 和 ExpressJs 无法分离错误和响应处理中使用的公共(public)代码

javascript - 在 setinterval 中使用长间隔时,Node.js 崩溃