Skip to content

Instantly share code, notes, and snippets.

@brainsik
Created December 13, 2012 21:31
Show Gist options
  • Save brainsik/4280136 to your computer and use it in GitHub Desktop.
Save brainsik/4280136 to your computer and use it in GitHub Desktop.
A simple way for Python cron tasks to exit if another process is currently running. Does not use a pidfile.
import os
import subprocess
import shlex
def bail_if_another_is_running():
cmd = shlex.split("pgrep -u {} -f {}".format(os.getuid(), __file__))
pids = subprocess.check_output(cmd).strip().split('\n')
if len(pids) > 1:
pids.remove("{}".format(os.getpid()))
print "Exiting! Found {} is already running (pids): {}".format(
__file__, " ".join(pids))
raise SystemExit(1)
@abhinaythurlapati
Copy link

Simple and elegant approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment