title: Running python script with cron only if not running
body: <p>I need to run a python script (job.py) every minute. This script must not be started if it is already running. Its execution time can be between 10 seconds and several hours.</p>
  
  <p>So I put into my crontab:</p>
  
  <pre><code>* * * * * root cd /home/lorenzo/cron &amp;&amp; python -u job.py 1&gt;&gt; /var/log/job/log 2&gt;&gt; /var/log/job/err
  </code></pre>
  
  <p>To avoid starting the script when it is already running, I use flock().</p>
  
  <p>This is the script (job.py):</p>
  
  <pre><code>import fcntl
  import time
  import sys
  
  def doIncrediblyImportantThings ():
      for i in range (100):
          sys.stdout.write ('[%s] %d.\n' % (time.strftime ('%c'), i) )
          time.sleep (1)
  
  if __name__ == '__main__':
      f = open ('lock', 'w')
      try: fcntl.lockf (f, fcntl.LOCK_EX | fcntl.LOCK_NB)
      except:
          sys.stderr.write ('[%s] Script already running.\n' % time.strftime ('%c') )
          sys.exit (-1)
      doIncrediblyImportantThings ()
  </code></pre>
  
  <p>This approach seems to work.</p>
  
  <p>Is there anything I am missing? Are there any troubles I can run into using this approach?</p>
  
  <p>Are there more advised or "proper" ways of achieving this behaviour?</p>
  
  <p>I thank you for any suggestion.</p>