Skip to content

Instantly share code, notes, and snippets.

@simonLeary42
Last active January 5, 2024 18:21
Show Gist options
  • Save simonLeary42/b6bf7088c5c38ed6b05b3c97b2eb3ed1 to your computer and use it in GitHub Desktop.
Save simonLeary42/b6bf7088c5c38ed6b05b3c97b2eb3ed1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# let's say you have a cron job that updates some cache and you'd like it to
# be updated often. You can measure the time it takes and set the cron frequency
# similar to that amount of time, but what if this machine is running slower one day?
# then, the last iteration of your job will still be running when the next
# iteration begins. What happens if they're both overwriting a file?
# What if the combined load of those two jobs slows down the computer even more,
# and then there are 3 jobs, and so on?
import os
import sys
import atexit
import hashlib
import subprocess
if len(sys.argv) != 2:
print("Exactly one argument required! Put your command in quotes.")
sys.exit(1)
command = sys.argv[1]
cmd_hash = hashlib.sha1(command.encode()).hexdigest()
lock_file_dirname = os.path.join('/tmp', os.getenv('USER', default="anybody"))
lock_file_path = os.path.join(lock_file_dirname, f'command-lock-{cmd_hash}')
if os.path.isfile(lock_file_path):
sys.exit(0)
if not os.path.isdir(lock_file_dirname):
os.makedirs(lock_file_dirname)
open(lock_file_path, 'w').close()
atexit.register(os.remove, lock_file_path)
subprocess.run(command, shell=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment