How To Monitor And Restart A Script Automatically?

Published July 13, 2024

Problem: Keeping Processes Running

Processes can crash or stop without warning, which can disrupt services and cause downtime. Restarting these processes by hand takes time and is not efficient, especially for important systems that need to run all the time.

Solution: Bash Script for Process Monitoring and Restart

Creating a Bash Script

A bash script can monitor and restart a Python script if it stops running. The main parts of this bash script include:

  • A loop that runs continuously
  • A command to check if the Python script is running
  • Logic to start the Python script if it's not running

The script checks if the Python process is running using the pgrep command. If the process is not found, the script starts it again. This method is simple for keeping a script running.

Tip: Logging for Troubleshooting

Add logging to your bash script to track when the Python script is restarted. This can help with troubleshooting and monitoring the frequency of restarts. You can do this by adding a line to write to a log file:

echo "$(date): Restarting $SCRIPT_NAME" >> /path/to/restart.log

Place this line just before the Python script is restarted in your bash script.

Implementing the Bash Script

Here's how to write the bash script:

  1. Open a text editor and create a new file named monitor_script.sh.

  2. Add this content to the file:

#!/bin/bash

SCRIPT_NAME="checkqueue.py"
SCRIPT_PATH="/path/to/checkqueue.py"

while true; do
    if ! pgrep -f "$SCRIPT_NAME" > /dev/null; then
        echo "Starting $SCRIPT_NAME"
        python3 "$SCRIPT_PATH" &
    fi
    sleep 60
done
  1. Save the file and make it executable with the command: chmod +x monitor_script.sh

Let's explain each part of the script:

  • #!/bin/bash tells the system to use bash to run this script.
  • SCRIPT_NAME and SCRIPT_PATH variables store the name and full path of the Python script.
  • The while true loop makes the script run continuously.
  • pgrep -f "$SCRIPT_NAME" checks if a process matching the script name is running.
  • If the process is not found, the script starts it using python3 "$SCRIPT_PATH" &.
  • The sleep 60 command makes the script wait for 60 seconds before checking again.

To use this script, replace /path/to/checkqueue.py with the actual path to your Python script. You can then run the bash script in the background or add it to your system's startup processes to keep your Python script running at all times.