0

I have a python script to do some auto works hosted in a Ubuntu 20.04 server I use the crontab to run it every 10 minutes , but the script is run twice and I have to kill the second one regularly.

Is there any none python solution to avoid this problem and make sure script runs only if not already running?

Raffa
  • 34,963

2 Answers2

1

Is there any none python solution to avoid this problem and make sure the script runs only if not already running?

Yes, in bash, you can check whether the script is running or not by the script's filename(used in the command to run the script) from within a bash shell script-file like so:

#!/bin/bash

if [ $(/bin/pgrep -f "script_file_name.sh") ]; then # Change "script_file_name.sh" to your actual script file name. echo "script running" # Command when the script is runnung else echo "script not running" # Command when the script is not running fi

or in a one line(that you can, directly, use in e.g. a crontab line) like so:

[ $(/bin/pgrep -f "script_file_name.sh") ] && echo "script running" || echo "script not running"
Raffa
  • 34,963
0

You may be suffering from a stalled zombie scripts. In which case you might still have problems because the zombie script will last forever until it is killed or the system is restarted. I use a utility called timeout in the crontab command to ensure the script can only run so long before it is killed which will ensure the next time cron tries to execute there won't be a zombie process.

timeout 1m sh -c 'python3 ik_api_timer.py kanaha'

this will only allow the script to run for 1 minute maximum before it is killed.

tavis
  • 101