timer.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # -*- coding:utf-8 -*-
  2. import time
  3. import requests
  4. import json
  5. from datetime import datetime
  6. class Timer(object):
  7. def __init__(self, sleep_interval=0.5):
  8. # '2018-09-28 22:45:50.000'
  9. # buy_time = 2020-12-22 09:59:59.500
  10. buy_time_everyday = global_config.getRaw('config', 'buy_time').__str__()
  11. localtime = time.localtime(time.time())
  12. self.buy_time = datetime.strptime(
  13. localtime.tm_year.__str__() + '-' + localtime.tm_mon.__str__() + '-' + localtime.tm_mday.__str__()
  14. + ' ' + buy_time_everyday,
  15. "%Y-%m-%d %H:%M:%S.%f")
  16. self.buy_time_ms = int(time.mktime(self.buy_time.timetuple()) * 1000.0 + self.buy_time.microsecond / 1000)
  17. self.sleep_interval = sleep_interval
  18. self.diff_time = self.local_jd_time_diff()
  19. def jd_time(self):
  20. """
  21. 从京东服务器获取时间毫秒
  22. :return:
  23. """
  24. url = 'https://a.jd.com//ajax/queryServerData.html'
  25. ret = requests.get(url).text
  26. js = json.loads(ret)
  27. return int(js["serverTime"])
  28. def local_time(self):
  29. """
  30. 获取本地毫秒时间
  31. :return:
  32. """
  33. return int(round(time.time() * 1000))
  34. def local_jd_time_diff(self):
  35. """
  36. 计算本地与京东服务器时间差
  37. :return:
  38. """
  39. return self.local_time() - self.jd_time()
  40. def start(self):
  41. while True:
  42. # 本地时间减去与京东的时间差,能够将时间误差提升到0.1秒附近
  43. # 具体精度依赖获取京东服务器时间的网络时间损耗
  44. if self.local_time() - self.diff_time >= self.buy_time_ms:
  45. break
  46. else:
  47. time.sleep(self.sleep_interval)
  48. if __name__ == "__main__":
  49. timer = Timer()
  50. print(timer.buy_time)