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",
.......
.......
}
}
]
}
You should use enviroment variables.
In your code you will check this env var:
if(process.env.WITH_SCHEDULE) {
...
}
When you start your instances, you will set WITH_SCHEDULE only for one instance.
Example pm2.json:
{
"apps": [
{
"name": "Example",
"script": "boot/app/app.js",
"args": [],
"error_file": "/srv/www.example.com/logs/error.log",
"out_file": "/srv/www.example.com/logs/info.log",
"ignore_watch": [
"node_modules"
],
"watch": false,
"cwd": "/srv/www.example.com/server",
"env": {
"NODE_ENV": "production",
"WITH_SCHEDULE": "1",
"HOST": "127.0.0.1",
"PORT": "9030"
}
},
{
"name": "Example",
"script": "boot/app/app.js",
"args": [],
"error_file": "/srv/www.example.com/logs/error.log",
"out_file": "/srv/www.example.com/logs/info.log",
"ignore_watch": [
"node_modules"
],
"watch": false,
"cwd": "/srv/www.example.com/server",
"env": {
"NODE_ENV": "production",
"HOST": "127.0.0.1",
"PORT": "9030"
}
}
]
}