Score:1

bash - Kill a processes if it has been running for more than one hour

mp flag

I have this bash script that runs a python program in Ubuntu server every 5 minutes if not already running , I want to make it kill the program if it has been running for more than one hour and rerun it.

#!/bin/bash

if pgrep -f "/home/user/crawler/panel/crawler/scans.py"
then
    echo "script running"
    # Command when the script is runnung
else
    echo "script not running"
    /home/user/crawler/env/bin/python /home/user/crawler/panel/crawler/scans.py
fi
hr flag
You may find the `timeout` program useful - see for example [Run and kill a bash program at a scheduled time](https://askubuntu.com/questions/1005636/run-and-kill-a-bash-program-at-a-scheduled-time)
urek mazino avatar
mp flag
that what i ended using , simple and onky need to edit one line
Score:0
jp flag

I modified your provided script to do what you want (quickly cooked but should do the job) ... I tried to comment as much as I thought needed, so please read the comments in the script below.

#!/bin/bash

if pgrep -f "/home/user/crawler/panel/crawler/scans.py"
then
    echo "script running"
    process_id=$(pgrep -f "/home/user/crawler/panel/crawler/scans.py") # Get the PID
    process_time=$(ps -p "$process_id" -o etime | awk -F":" 'NR==2 && NF>2{print 1}') # Get process elapsed time and print "1" if more than an houer
    [ "$process_time" == 1 ] && kill "$process_id" && /home/user/crawler/env/bin/python /home/user/crawler/panel/crawler/scans.py # If the process has been running for more than one hour then kill it and run the script again
    # Command when the script is runnung
else
    echo "script not running"
    /home/user/crawler/env/bin/python /home/user/crawler/panel/crawler/scans.py
fi
urek mazino avatar
mp flag
i ended using timeout function before running the python script and seems working so far , I'll keep your solution as secondary plan
Raffa avatar
jp flag
@urekmazino I am happy to help, but there is one important thing that you should keep in mind though … While `timeout` will work to kill your python program after one hour, there will be times when it will not be running for up to five minutes until your bash script runs it again … But my solution will kill it and then run it immediately thus minimizing down time :-)
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.