Skip to content

Commit

Permalink
async sync method
Browse files Browse the repository at this point in the history
  • Loading branch information
beasteers committed Oct 31, 2023
1 parent 1e4f892 commit dcbd9ec
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions redis_record/sync.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import time
import datetime
import asyncio
import logging

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)

class Sync:
def __init__(self, speed_fudge=1, warn_above=10):
Expand Down Expand Up @@ -30,16 +34,29 @@ def wait_time(self, timestamp):
def sync(self, timestamp):
delay = self.wait_time(timestamp)
if delay:
if delay > self.warn_above:
print(
f"\n\nWarning: sleeping for {delay:.3f} seconds. \n"
f"Simulating {datetime.datetime.fromtimestamp(self.tpub).strftime('%H:%M:%S.%f')} - {datetime.datetime.fromtimestamp(timestamp).strftime('%H:%M:%S.%f')}")
self._warn(timestamp, delay)
time.sleep(delay / self.speed_fudge)

# update for next iteration
self.tpub = timestamp
self.tproc = time.time()

async def sync_async(self, timestamp):
delay = self.wait_time(timestamp)
if delay:
self._warn(timestamp, delay)
await asyncio.sleep(delay / self.speed_fudge)

# update for next iteration
self.tpub = timestamp
self.tproc = time.time()

def _warn(self, timestamp, delay):
if delay > self.warn_above:
log.warning(
f"Sleeping for {delay:.3f} seconds. \n"
f"Simulating {datetime.datetime.fromtimestamp(self.tpub).strftime('%H:%M:%S.%f')} - {datetime.datetime.fromtimestamp(timestamp).strftime('%H:%M:%S.%f')}")


class Clock(Sync):
def __init__(self, rate=None):
Expand All @@ -53,6 +70,9 @@ def wait_time(self, timestamp=None):
def sync(self, timestamp=None):
return super().sync(self.tpub + self.delta)

async def sync_async(self, timestamp=None):
return await super().sync_async(self.tpub + self.delta)

def nowait_sync(self, timestamp=None):
if not self.wait_time(timestamp):
self.sync(timestamp)
Expand Down

0 comments on commit dcbd9ec

Please sign in to comment.