Bläddra i källkod

Streamlined the client's polling task by using utils.cron_config

Signed-off-by: Stan Janssen <stan.janssen@elaad.nl>
Stan Janssen 4 år sedan
förälder
incheckning
acb0453b17
3 ändrade filer med 22 tillägg och 27 borttagningar
  1. 4 22
      openleadr/client.py
  2. 14 5
      openleadr/utils.py
  3. 4 0
      test/test_utils.py

+ 4 - 22
openleadr/client.py

@@ -25,7 +25,6 @@ import ssl
 from datetime import datetime, timedelta, timezone
 from functools import partial
 from http import HTTPStatus
-from random import randint
 
 import aiohttp
 from lxml.etree import XMLSyntaxError
@@ -131,32 +130,15 @@ class OpenADRClient:
         await self._poll()
 
         # Set up automatic polling
-        if self.poll_frequency.total_seconds() < 60:
-            seconds_offset = randint(0, self.poll_frequency.seconds)
-            cron_second = f"{seconds_offset}/{self.poll_frequency.seconds}"
-            cron_minute = "*"
-            cron_hour = "*"
-        elif self.poll_frequency.total_seconds() < 3600:
-            cron_second = randint(0, 59)
-            cron_minute = f'*/{int(self.poll_frequency.total_seconds() / 60)}'
-            cron_hour = "*"
-        elif self.poll_frequency.total_seconds() < 86400:
-            cron_second = randint(0, 59)
-            cron_minute = "0"
-            cron_hour = f'*/{int(self.poll_frequency.total_seconds() / 3600)}'
-        elif self.poll_frequency.total_seconds() > 86400:
+        if self.poll_frequency > timedelta(hours=24):
             logger.warning("Polling with intervals of more than 24 hours is not supported. "
                            "Will use 24 hours as the logging interval.")
-            cron_second = randint(0, 59)
-            cron_minute = "0"
-            cron_hour = "0"
-            return
+            self.poll_frequency = timedelta(hours=24)
+        cron_config = utils.cron_config(self.poll_frequency, randomize_seconds=True)
 
         self.scheduler.add_job(self._poll,
                                trigger='cron',
-                               second=cron_second,
-                               minute=cron_minute,
-                               hour=cron_hour)
+                               **cron_config)
         self.scheduler.start()
 
     async def stop(self):

+ 14 - 5
openleadr/utils.py

@@ -18,6 +18,7 @@ from datetime import datetime, timedelta, timezone
 from dataclasses import is_dataclass, asdict
 from collections import OrderedDict
 from openleadr import enums
+from random import randint
 import asyncio
 import itertools
 import re
@@ -472,22 +473,30 @@ def group_by(list_, key, pop_key=False):
     return grouped
 
 
-def cron_config(interval):
+def cron_config(interval, randomize_seconds=False):
     """
     Returns a dict with cron settings for the given interval
     """
+    if randomize_seconds:
+        seconds_offset = min(60, randint(0, interval.total_seconds()))
+    else:
+        seconds_offset = "*"
     if interval < timedelta(minutes=1):
-        second = f"*/{interval.seconds}"
+        second = f"{seconds_offset}/{interval.seconds}"
         minute = "*"
         hour = "*"
     elif interval < timedelta(hours=1):
-        second = "0"
+        second = f"{seconds_offset}" if randomize_seconds else "0"
         minute = f"*/{int(interval.total_seconds()/60)}"
         hour = "*"
-    elif interval < timedelta(days=1):
-        second = "0"
+    elif interval < timedelta(hours=24):
+        second = f"{seconds_offset}" if randomize_seconds else "0"
         minute = "0"
         hour = f"*/{int(interval.total_seconds()/3600)}"
+    else:
+        second = f"{seconds_offset}" if randomize_seconds else "0"
+        minute = "0"
+        hour = "0"
     return {"second": second, "minute": minute, "hour": hour}
 
 

+ 4 - 0
test/test_utils.py

@@ -104,4 +104,8 @@ def test_cron_config():
     assert utils.cron_config(timedelta(minutes=5)) == {'second': '0', 'minute': '*/5', 'hour': '*'}
     assert utils.cron_config(timedelta(hours=1)) == {'second': '0', 'minute': '0', 'hour': '*/1'}
     assert utils.cron_config(timedelta(hours=2)) == {'second': '0', 'minute': '0', 'hour': '*/2'}
+    assert utils.cron_config(timedelta(hours=25)) == {'second': '0', 'minute': '0', 'hour': '0'}
+
+    cron_config = utils.cron_config(timedelta(seconds=5), randomize_seconds=True)
+    assert int(cron_config['second'][0]) <= 5