Files
tg-admin-bot/lock_utils.py

30 lines
612 B
Python

from pathlib import Path
import os
import time
LOCK_DIR = Path("/var/run/tg-bot")
LOCK_DIR.mkdir(parents=True, exist_ok=True)
def lock_path(name: str) -> Path:
return LOCK_DIR / f"{name}.lock"
def acquire_lock(name: str) -> bool:
p = lock_path(name)
try:
fd = os.open(str(p), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except FileExistsError:
return False
try:
os.write(fd, str(time.time()).encode("ascii", errors="ignore"))
finally:
os.close(fd)
return True
def release_lock(name: str):
p = lock_path(name)
if p.exists():
p.unlink()