I have a python file which should ideally run at all times. However, sometimes it crashes, so I would have to start it again. Therefore, I have a cronjob that should try to run every 5 minutes (if it crashes it would restart again always within 5 minutes at least):
*/5 * * * * bash my_script.sh
that runs the following bash script called my_script.sh:
#!/bin/bash
now=$(date +"%T")
if ! pgrep -f 'filename.py'
then
echo "$now: filename was not running, started filename" >> crontab_errors.log
/home/ubuntu/envs/my_virtual_env/bin/python /home/ubuntu/filename.py arg1
else
echo "$now: filename was already running" >> crontab_errors.log
fi
The bash script works great when used alone, so it starts the code if it is the first instance, and if I would start another, it would mention that the filename was already running.
However, this behavior is not seen in crontab. There, it continuously mentions that the file is already running, while easy inspecting with the top
command clearly shows that there is no python process called 'filename.py' running. It is also visible in the log that I create, called crontab_errors:
17:55:01: filename was already running
18:00:01: filename was already running
18:05:01: filename was already running
What am I missing here? My goal is just to always be sure that only 1 instance of filename.py is running because otherwise the code crashes.
Thanks in advance!