CalcBase.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import redis
  2. import time as time
  3. import logging
  4. import json
  5. from .DataStream import span_days
  6. import logging
  7. logger = logging.getLogger('CalcBase')
  8. class CalcBase(object):
  9. def __init__(self):
  10. self._mQuit = False
  11. self._mRHost = ''
  12. self._mRPort = 6379
  13. def set_redis(self, rhost, rport):
  14. self._mRHost = rhost
  15. self._mRPort = rport
  16. def stop(self):
  17. self._mquit = True
  18. def _calc_handler(self, rclient):
  19. pass
  20. def _reader(self):
  21. return None
  22. def run(self):
  23. def redis_client():
  24. pool = redis.ConnectionPool(host=self._mRHost, port=self._mRPort)
  25. client = redis.Redis(connection_pool=pool)
  26. return client
  27. client = None
  28. loop = 0;
  29. while self._mQuit == False:
  30. try:
  31. if client is None:
  32. client = redis_client()
  33. self._calc_handler(client)
  34. except redis.RedisError as ex:
  35. logger.error(ex)
  36. except Exception as ex:
  37. logger.error(ex)
  38. finally:
  39. time.sleep(1)
  40. loop += 1
  41. def calc_time(self, reader, start_time: int, end_time: int):
  42. end_time = reader.near_stamp(end_time, False)
  43. if end_time is None:
  44. raise Exception('end_time data is empty')
  45. start_time = reader.near_stamp(start_time, True)
  46. if start_time is None:
  47. raise Exception('start_time data is empty')
  48. strtime = lambda t: time.strftime('%d-%H:%M:%S', time.localtime(t))
  49. logger.debug("near_stamp start_time %s end_time=%s", strtime(start_time), strtime(end_time))
  50. if start_time >= end_time:
  51. raise Exception('start_time equal endtime')
  52. days = span_days(start_time, end_time)
  53. strtime = lambda t: time.strftime('%d-%H:%M:%S', time.localtime(t))
  54. sdays = [strtime(day) for day in days]
  55. logger.debug(sdays)
  56. return days, start_time, end_time