My question is how to use node-schedule to run a cron only on one instance out of two instances of node server. Currently it is running on both instances but I want it to be executed only on one instance. So How can you make a cluster run a task only once? Thanks in advance.
{
"apps": [
{
"name": "Example",
"script": "boot/app/app.js",
"watch": false,
"exec_mode": "cluster_mode",
"instances": 2,
"merge_logs": true,
"cwd": "/srv/www.example.com/server",
"env": {
"NODE_ENV": "development",
.......
.......
}
}
]
}
To create our email scheduler application insert the following code into the index. js file: const express = require("express"); const cron = require("node-cron"); const nodemailer = require("nodemailer"); app = express(); //send email after 1 minute cron.
It's not possible to run cron in every second but we can run cron in every second using this method, we use a sleep command before the echo date. Cron - Cron is command name that runs scheduled action using the crond daemon.
node-cron syntax It is a package used to schedule tasks (functions or commands) in Node. js. Its name is derived from the Greek word 'Chronos' meaning time. These tasks can be scheduled to either run once or repeatedly.
You can use an environment variable provided by PM2 itself called NODE_APP_INSTANCE
which requires PM2 2.5.
NODE_APP_INSTANCE
environment variable is used to determine difference between process, for example you may want to run a cronjob only on one process, you can just check if process.env.NODE_APP_INSTANCE === 0, Since two processes can never have the same number.
More Info on PM2 official doc here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With