PM2 restart job on sucess

I have a puppeteer script that I am running on production using PM2. I need to restart it when the last job is a success or failure. Each bot instance is a cluster of 22 more bots. I want to restart it whenever it is finished.

The bots do many random things so I can not set up a cron job to restart them as the bot can finish in few seconds or in a few minutes.

I am open to any other library that helps me accomplish this.

{
    "apps": [
        {
            "name": "bot-1",
            "script": "Bot1.js",
            "instances": "2",
            "autorestart": true,
            "restart_delay": 1,
            "exec_mode" : "cluster"
        },
        {
            "name": "bot-2",
            "script": "Bot1.js",
            "instances": "2",
            "autorestart": true,
            "restart_delay": 1,
            "exec_mode" : "cluster"
        },
        {
            "name": "bot-3",
            "script": "Bot1.js",
            "instances": "2",
            "autorestart": true,
            "restart_delay": 1,
            "exec_mode" : "cluster"
        },
        {
            "name": "bot-4",
            "script": "Bot1.js",
            "instances": "2",
            "autorestart": true,
            "restart_delay": 1,
            "exec_mode" : "cluster"
        },
        {
            "name": "bot-5",
            "script": "Bot1.js",
            "instances": "2",
            "exec_mode" : "cluster",
            "autorestart": true,
            "restart_delay": 1,
        },{
            "name": "bot-6",
            "script": "Bot1.js",
            "instances": "2",
            "autorestart": true,
            "restart_delay": 1,
            "exec_mode" : "cluster"
        },
        {
            "name": "bot-7",
            "script": "Bot1.js",
            "instances": "2",
            "autorestart": true,
            "restart_delay": 1,
            "exec_mode" : "cluster"
        },
        {
            "name": "bot-8",
            "script": "Bot1.js",
            "instances": "2",
            "autorestart": true,
            "restart_delay": 1,
            "exec_mode" : "cluster"
        },
        {
            "name": "bot-9",
            "script": "Bot1.js",
            "instances": "2",
            "autorestart": true,
            "restart_delay": 1,
            "exec_mode" : "cluster"
        },
        {
            "name": "bot-10",
            "script": "Bot1.js",
            "instances": "2",
            "exec_mode" : "cluster",
            "autorestart": true,
            "restart_delay": 1
        }
    ]
}

Answer

You can use the pm2 api to accomplish this (pm2.restart(process, [options], fn)). In your bot code – you could implement a teardown function, which restarts the pm2 process.

In order to restart the current process, the bot is running in, you could pass in the name as an env variable.