我已经为自己构建了一个随机的 qoute 生成器,它每天都会发送一封带有报价的电子邮件。为了构建它,我使用了 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()
函数应该只运行一次。
谢谢你。