Ad

Node Schedule Runs Task Too Many Times

- 1 answer

I've built myself a random qoute generator that sends an email every day with a quote. To build that, I used the node-schedule package.

I specified it that every day at 16:00 it should execute a function:

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

But turns out that it does that for a lot of times, not only once.

What's the problem?

Here's the full code:

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: "[email protected]", // generated ethereal user
      pass: "123456" // generated ethereal password
    }
  });

  // send mail with defined transport object
  let info = await transporter.sendMail(
    {
      from: '"John doe 👍" <[email protected]>', // sender address
      to: "[email protected]", // 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}`));

So, for the result I expect that this scheduler() function should only run once.

Thank you.

Ad

Answer

You need to pass minutes and seconds (optional) as well. "* * 16 * * *" means it will run at every minute and every second from 16:00 till 17:00. So you need to correct time like this

schedule.scheduleJob("0 16 * * *", () => {
  scheduler();
  console.log("hey");
});
Ad
source: stackoverflow.com
Ad