#StackBounty: #bash #cron #startup #pm2 Delay start of process with pm2 until cron time

Bounty: 50

I’m setting up two scripts to use pm2 to restart all our processes at 8:00pm on Saturday on all servers, and stop all processes at 10:00pm everyday on the dev server. This is to help control resource use for ongoing processes, as well as remove processes that are not used often in development.

So far, I have the pm2 config to prevent an autorestart, and then run two scripts on a cron_restart schedule, which restart and stop the services with some separation between them. They work fine together, but I need to account for when the server reboots, or if the service ever goes down and I need to bring it back up; at that initial start, both services will restart at the same time. As such, I would rather delay the start of both services until their proper Cron schedule. I know that pm2 has restart_delay, but that seems to work like sleep and is for the restart, not the initial start up. Has anyone ever had a use-case like this?

My scripts are as follows:

pm2_config.json

{
  "apps" : [
    {
      "name" : "pm2restart",
      "script" : "restart.sh",
      "cron_restart": "0 19 * * Sat",
      "autorestart": false,
      "pid_file": "~/apps/pm2appcontrol/bin/pm2restart.pid",
      "out_file": "~/apps/logs/pm2appcontrol/pm2restart.log",
      "error_file": "~/apps/logs/pm2appcontrol/pm2restart.log",
      "log_date_format" : "YYYY-MM-DD HH:mm:ss"
    },
    {
      "name" : "pm2stop",
      "script" : "stop.sh",
      "cron_restart": "0 21 * * *",
      "autorestart": false,
      "pid_file": "~/apps/pm2appcontrol/bin/pm2stop.pid",
      "out_file": "~/apps/logs/pm2appcontrol/pm2stop.log",
      "error_file": "~/apps/logs/pm2appcontrol/pm2stop.log",
      "log_date_format" : "YYYY-MM-DD HH:mm:ss"
    }
  ]
}

This is run with the script:

#!/bin/bash

pm2 start ./pm2_config.json

The two scripts in the config file are simply:

#!/bin/bash

#pm2restart


for appName in $HOME/apps/* ; do
    service=$(basename "$appName")
    if [ $service != pm2apprestart ] && [ $service != haproxy ]
    then
        echo "Restarting $service"
        pm2 restart /$service/
    else
        echo "======================"
        echo "Skipping $service"
        echo "======================"
    fi
done

and

#!/bin/bash

#pm2stop

for appName in $HOME/apps/* ; do
    service=$(basename "$appName")
    if [ $service != pm2apprestart ] && [ $service != haproxy ]
    then
        echo "Stopping $service"
        pm2 stop /$service/
    else
        echo "======================"
        echo "Skipping $service"
        echo "======================"
    fi
done


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.