DeaD_EyE

QueryScheduler with two modes

Jan 28th, 2020
178
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import time
  2.  
  3.  
  4. class QueryScheduler:
  5.     NORMAL = 'normal'
  6.     LIVE = 'live'
  7.  
  8.     def __init__(self, queries_normal, queries_live):
  9.         self.mode = self.NORMAL
  10.         self.queries_normal = queries_normal
  11.         self.queries_live = queries_live
  12.         self.waiting = self._in_waiting()
  13.  
  14.     def __iter__(self):
  15.         return self
  16.  
  17.     def __next__(self):
  18.         time.sleep(0.1)
  19.         current_queries = [query for (query, freq, after) in self.waiting if time.time() > after]
  20.         self.waiting = [
  21.             (
  22.                 query,
  23.                 freq,
  24.                 time.time() + freq if time.time() > after else after,
  25.             )
  26.             for query, freq, after in self.waiting
  27.         ]
  28.         return current_queries
  29.  
  30.     def _in_waiting(self):
  31.         if self.mode == self.NORMAL:
  32.             queries = self.queries_normal
  33.         elif self.mode == self.LIVE:
  34.             queries = self.queries_live
  35.         return [(query, freq, time.time() + freq) for query, freq in queries]
  36.  
  37.     def switch(self, mode):
  38.         if self.mode == mode:
  39.             return
  40.         self.mode = mode
  41.         self.waiting = self._in_waiting()
  42.  
  43.  
  44. qs = QueryScheduler(
  45.     [
  46.         ('A', 10),
  47.         ('B', 10),
  48.         ('C', 10),
  49.         ('D', 10),
  50.     ],
  51.     [
  52.         ('A', 1),
  53.         ('B', 5),
  54.         ('C', 10),
  55.         ('D', 15),
  56.     ]
  57. )
  58.  
  59. qs.switch(QueryScheduler.NORMAL)
  60. for q in qs:
  61.     if not q:
  62.         continue
  63.     print(q)
  64.     # mode switch to LIVE
  65.     if qs.mode == QueryScheduler.NORMAL:
  66.         qs.switch(QueryScheduler.LIVE)
RAW Paste Data