-
Notifications
You must be signed in to change notification settings - Fork 948
/
timer.py
53 lines (45 loc) · 1.74 KB
/
timer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# -*- coding:utf-8 -*-
import time
import requests
import json
from datetime import datetime
from jd_logger import logger
from config import global_config
class Timer(object):
def __init__(self, sleep_interval=0.5):
# '2018-09-28 22:45:50.000'
self.buy_time = datetime.strptime(global_config.getRaw('config','buy_time'), "%Y-%m-%d %H:%M:%S.%f")
self.buy_time_ms = int(time.mktime(self.buy_time.timetuple()) * 1000.0 + self.buy_time.microsecond / 1000)
self.sleep_interval = sleep_interval
self.diff_time = self.local_jd_time_diff()
def jd_time(self):
"""
从京东服务器获取时间毫秒
:return:
"""
url = 'https://a.jd.com//ajax/queryServerData.html'
ret = requests.get(url).text
js = json.loads(ret)
return int(js["serverTime"])
def local_time(self):
"""
获取本地毫秒时间
:return:
"""
return int(round(time.time() * 1000))
def local_jd_time_diff(self):
"""
计算本地与京东服务器时间差
:return:
"""
return self.local_time() - self.jd_time()
def start(self):
logger.info('正在等待到达设定时间:{},检测本地时间与京东服务器时间误差为【{}】毫秒'.format(self.buy_time, self.diff_time))
while True:
# 本地时间减去与京东的时间差,能够将时间误差提升到0.1秒附近
# 具体精度依赖获取京东服务器时间的网络时间损耗
if self.local_time() - self.diff_time >= self.buy_time_ms:
logger.info('时间到达,开始执行……')
break
else:
time.sleep(self.sleep_interval)