How to use node -schedule to run cron on only one instance?

My question is how to use node -schedule to run cron on only one instance of two node server instances. It currently works on both instances, but I want it to run on only one instance. So how to 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", ....... ....... } } ] } 
+6
source share
2 answers

You must use environment variables.

In your code, you check this env var:

 if(process.env.WITH_SCHEDULE) { ... } 

When you start your instances, you set WITH_SCHEDULE for only 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" } } ] } 
+2
source

You can use the environment variable provided by PM2 called NODE_APP_INSTANCE , which requires PM2 2.5.

NODE_APP_INSTANCE environment variable is used to determine the difference between the process, for example, you can run cronjob on only one process, you can just check if process.env.NODE_APP_INSTANCE === 0 is not possible, since two processes can never have the same number.

More information on PM2 white paper here .

0
source

Source: https://habr.com/ru/post/1012028/


All Articles