schedule to run a cron only on one instance?
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"
}
}
]
}
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.
链接地址: http://www.djcxy.com/p/37034.html上一篇: 为Android应用创建3D动画
下一篇: 计划只在一个实例上运行cron?