2019-10-10 11:10:45 +00:00
|
|
|
import datetime, os
|
|
|
|
from src import PollHook, utils
|
|
|
|
|
|
|
|
EXPIRATION = 60 # 1 minute
|
|
|
|
|
|
|
|
class LockFile(PollHook.PollHook):
|
2019-10-17 11:39:56 +00:00
|
|
|
def __init__(self, filename: str):
|
|
|
|
self._filename = filename
|
2019-10-10 11:10:45 +00:00
|
|
|
self._next_lock = None
|
|
|
|
|
|
|
|
def available(self):
|
|
|
|
now = utils.datetime_utcnow()
|
2019-10-17 11:39:56 +00:00
|
|
|
if os.path.exists(self._filename):
|
|
|
|
with open(self._filename, "r") as lock_file:
|
2019-10-10 11:10:45 +00:00
|
|
|
timestamp_str = lock_file.read().strip().split(" ", 1)[0]
|
|
|
|
|
|
|
|
timestamp = utils.iso8601_parse(timestamp_str)
|
|
|
|
|
|
|
|
if (now-timestamp).total_seconds() < EXPIRATION:
|
|
|
|
return False
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
def lock(self):
|
2019-10-17 11:39:56 +00:00
|
|
|
with open(self._filename, "w") as lock_file:
|
2019-10-10 11:10:45 +00:00
|
|
|
last_lock = utils.datetime_utcnow()
|
|
|
|
lock_file.write("%s" % utils.iso8601_format(last_lock))
|
|
|
|
self._next_lock = last_lock+datetime.timedelta(
|
|
|
|
seconds=EXPIRATION/2)
|
|
|
|
|
|
|
|
def next(self):
|
|
|
|
return max(0, (self._next_lock-utils.datetime_utcnow()).total_seconds())
|
|
|
|
def call(self):
|
2019-10-10 13:12:58 +00:00
|
|
|
self.lock()
|
2019-10-10 11:10:45 +00:00
|
|
|
|
|
|
|
def unlock(self):
|
2019-10-17 11:39:56 +00:00
|
|
|
if os.path.isfile(self._filename):
|
|
|
|
os.remove(self._filename)
|