Skip to content

Instantly share code, notes, and snippets.

@abdusco
Created November 21, 2018 15:32
Show Gist options
  • Save abdusco/2afa5c552afd423405e6f47c6881506d to your computer and use it in GitHub Desktop.
Save abdusco/2afa5c552afd423405e6f47c6881506d to your computer and use it in GitHub Desktop.
Run only a single instance of given function
import tempfile
import os
from pathlib import Path
def singleton(callback: callable, instance_name: str):
tempdir = Path(tempfile.gettempdir())
lockfile = tempdir / f'{instance_name}.lock'
try:
if lockfile.exists():
lockfile.unlink()
except WindowsError:
print(f'Another instance of {instance_name} is already running')
os._exit(1)
with open(lockfile, 'wb') as handle:
callback()
lockfile.unlink()
@abdusco
Copy link
Author

abdusco commented Nov 21, 2018

Usage:

singleton(main,
          instance_name='myapp')

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