HHH HHH - 2 months ago 10
Bash Question

Cron Job Killing and Restarting Python Script

I set up a cron job on a linux server to kill and restart a python script (run.py) every other day. I set the job to run as root, but I find that sometimes it doesn't kill the process properly (and ends up running two scripts in a row).

Is there a better way to do this?

My cron job parameters:

0 8 * * 1,4,7 cd /home/myUser && ./start.sh


echo "Running..."
sudo pkill -f run.py
sudo python run.py &

Answer Source

I guess run.py runs as python, not run.py. So you won't find anything with kill -f run.py.

You should echo the PID of the process to a file and use that value to kill the previous process if it's still running. Just add echo $! >/path/to/pid.file as the last line in your start.sh script to do so.

Read more:

Example to get you started:

echo "Running..."
sudo pkill -F /path/to/pid.pid
sudo python /path/to/run.py &
echo $! > /path/to/pid.pid