1

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

start.sh:

#!/bin/bash
echo "Running..."
sudo pkill -f run.py
sudo python run.py &
HHH
  • 149
  • 2
  • 12

2 Answers2

3

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:

#!/bin/bash
echo "Running..."
sudo pkill -F /path/to/pid.pid
sudo python /path/to/run.py &
echo $! > /path/to/pid.pid
Community
  • 1
  • 1
Bjorn
  • 5,272
  • 1
  • 24
  • 35
  • do i need the sudo ? – George Pamfilis Dec 17 '19 at 16:34
  • @GeorgePamfilis for `pkill`, only if the process was started by another user than the user starting the cron. For `python`, only if the script requires elevated permissions. Good practice: start without, add if it doesn't work. – Bjorn Dec 17 '19 at 20:18
0

Another alternative to this is making the python script run on upstart if you are on a system that supports upstart. Then you can just do sudo /sbin/start job_name at the begin and sudo /sbin/stop job_name this makes upstart manage the pids for you.

Python upstart script Upstart python script

ford prefect
  • 7,096
  • 11
  • 56
  • 83