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
  • 32,237
Stuart gow
  • 11
  • 1
  • 3
  • 1
    the script runs twice starting at the same time? that's an issue with cron or with the way you set it up. Or do you mean that it sometimes runs for longer than 10 minutes? maybe you want to run it less frequently then? – Esther Jul 21 '22 at 02:02
  • yeah if the script after 10 minutes keeps running it will execute again – Stuart gow Jul 21 '22 at 05:09
  • Bash? checking this inside the script is better as it catches ALL attempts to start it while already running not just cron, See the socket module and socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) – Rinzwind Jul 21 '22 at 06:19
  • 1
    Your title is not reflecting the specific problem, you may want to edit your title. – vanadium Jul 21 '22 at 07:39

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
  • 32,237
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