【发布时间】:2023-01-07 06:58:44
【问题描述】:
完整的新手在这里对我如此裸露。我有许多设备向单个位置报告状态更新,并且随着更多站点的添加,随 time.sleep(x) 的漂移变得越来越明显,并且随着现在连接的站点越来越多,它已经完全翻了一番迭代之间的休眠时间。
import time
...
def client_list():
sites=pandas.read_csv('sites')
return sites['Site']
def logs(site):
time.sleep(x)
if os.path.isfile(os.path.join(f'{site}/target/', 'hit')):
stamp = time.strftime('%Y-%m-%d,%H:%M:%S')
log = open(f"{site}/log", 'a')
log.write(f",{stamp},{site},hit\n")
log.close()
os.remove(f"{site}/target/hit")
else:
stamp = time.strftime('%Y-%m-%d,%H:%M:%S')
log = open(f"{site}/log", 'a')
log.write(f",{stamp},{site},miss\n")
log.close()
...
if __name__ == '__main__':
while True:
try:
client_list()
with concurrent.futures.ThreadPoolExecutor() as executor:
executor.map(logs, client_list())
...
我确实尝试用这个添加漂移计算:
from datetime import datetime, timedelta
def logs(site):
first_called=datetime.now()
num_calls=1
drift=timedelta()
time_period=timedelta(seconds=5)
while 1:
time.sleep(n-drift.microseconds/1000000.0)
current_time = datetime.now()
num_calls += 1
difference = current_time - first_called
drift = difference - time_period* num_calls
if os.path.isfile(os.path.join(f'{site}/target/', 'hit')):
...
它以日志中的重复条目结束,并且该过程仍然漂移。 有没有更好的方法来安排函数每 x 秒运行一次并考虑开始时间的漂移?
【问题讨论】:
-
time.sleep(n-drift.microseconds/1000000.0) --> 'n' 是什么?
-
抱歉,这与上面的 time.sleep(x) 相同;所以5秒。
-
所以 n = time_period in time.sleep(n-drift.microseconds/1000000.0) ??
标签: python python-3.x python-multithreading concurrent.futures sched