diff options
| author | 2019-10-10 12:10:45 +0100 | |
|---|---|---|
| committer | 2019-10-10 12:11:03 +0100 | |
| commit | 2c19bdb94997f36231c854441ad2b78f00dbaff6 (patch) | |
| tree | 752574a6d1f18dd44b704d864f9c687ad2a8f7fd /src/LockFile.py | |
| parent | refactor multi-line-to-line normalisation to utils.parse.line_normalise(), us... (diff) | |
| signature | ||
add a fairly basic file locking mechanism with src/LockFile.py
closes #96
Diffstat (limited to 'src/LockFile.py')
| -rw-r--r-- | src/LockFile.py | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/src/LockFile.py b/src/LockFile.py new file mode 100644 index 00000000..9f53b8d5 --- /dev/null +++ b/src/LockFile.py @@ -0,0 +1,40 @@ +import datetime, os +from src import PollHook, utils + +EXPIRATION = 60 # 1 minute + +class LockFile(PollHook.PollHook): + def __init__(self, database_location: str): + self._database_location = database_location + self._lock_location = "%s.lock" % database_location + self._next_lock = None + + def available(self): + now = utils.datetime_utcnow() + if os.path.exists(self._lock_location): + with open(self._lock_location, "r") as lock_file: + 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): + with open(self._lock_location, "w") as lock_file: + 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): + if self.next() == 0: + self.lock() + + def unlock(self): + if os.path.isfile(self._lock_location): + os.remove(self._lock_location) |
