Thursday, February 3, 2022

[SOLVED] Node cron job executions duplicates

Issue

There are two bots that are hosted on Ubuntu server 18.04 x64 (1 core) and supported by PM2 (fork). rel="nofollow noreferrer">https://dl4.joxi.net/drive/2020/01/07/0028/2950/1842054/54/ed0a34751d.jpg One of them is scheduled to run tasks using Cron, in the example will be - Quotes (MainBotDP).

At 9 a.m. of each day, a script is executed which should send the quote once (executed once a day). Instead, the script runs multiple times (not always) and sends several quotes.

I noticed a pattern that it seems to happen when I reboot the bot several times during the day and the next day the script runs depending on the number of reboots (I'm not sure, I guess). I don't quite understand how to solve this situation, I would be grateful for your help!

PM2 Config file

module.exports = {
  apps: [
    {
      name: "MainBotDP",
      cwd: "./digitalPilgrims/src/",
      script: "index.js",
      instance_var: "INSTANCE_ID",
      autorestart: true,
      watch: false,
      max_memory_restart: "1G",
      env: {
        WITH_SCHEDULE: "1"
      }
    },
    {
      name: "RSSNews",
      cwd: "./discordNews/",
      script: "server.js",
      instance_var: "INSTANCE_ID",
      autorestart: true,
      watch: false,
      max_memory_restart: "1G",
      env: {
        WITH_SCHEDULE: "2"
      }
    }
  ]
};

Cron schedule file

const CronJob = require("cron").CronJob;
const { quoteOfDay } = require("./quote");
const { holidayNewYear } = require("./holidays");
const { monthlyGameStats } = require("./monthlyStats");

function startCrons(guild) {
  if (process.env.WITH_SCHEDULE === "1") {
    const cronQuote = new CronJob(
      "0 0 9 * * *",
      function() {
        quoteOfDay(guild);
      },
      false,
      false,
      "Europe/Moscow"
    );

    const cronHolidayNewYear = new CronJob({
      cronTime: "0 18 15 1 0 *",
      onTick: function() {
        holidayNewYear(guild);
      },
      start: false,
      timeZone: "Europe/Moscow"
    });

    const cronMonthlyGameStats = new CronJob(
      "0 10 1 * *",
      function() {
        monthlyGameStats(guild);
      },
      false,
      false,
      "Europe/Moscow"
    );
    cronQuote.start();
    cronHolidayNewYear.start();
    cronMonthlyGameStats.start();
  }
}

module.exports = {
  startCrons
};

Solution

The problem was that function that starts Crons was running in "process.on". Аfter changing to "process.once", the messages are no longer duplicated.



Answered By - sayrecs
Answer Checked By - Candace Johnson (WPSolving Volunteer)