在无限循环中,是否有任何模块可以将其中一个变量的函数临时挂起特定时间(例如 10 分钟)?



我有一个无限循环运行的代码,从外部源收集实时数据。

while True:
x = Livedata() # this should stop for 10 mins when x < 30, then restart.
y = Livedata()
z = Livedata()

我希望代码暂停收集数据N分钟 当满足某个条件时,对于x变量,例如x < 30. 当x挂起时,代码不应停止收集yz的数据。N分钟后,再次收集x数据,直到再次满足条件。

我认为线程是最好的选择,但如果你想要一种无线程的方式,你可以使用类似time.time()的东西来跟踪你想做的每件事的每个开始时刻。

如果x > 30,这将始终运行x代码,否则它会跳过x = liveData()10 分钟。10 分钟后,它将重新启动。yz只是做他们已经做过的事情。

import time
def minutesPast(end_time, start_time):
return ( end_time - start_time ) / 60
TIME_INTERVAL = 10 # minutes
x_start = time.time()
# your loop
while True:
time_now = time.time()
# code for 'x'
if ( x > 30 ) or (minutesPast(time_now, x_start) > TIME_INTERVAL) :
x_start = time.time()
x = liveData()
y = liveData()
z = liveData()

您可以将多处理与threading模块一起使用:

from threading import Thread
from time import sleep
x = Thread(target=Livedata)
y = Thread(target=Livedata)
z = Thread(target=Livedata)
y.start() # Start y
z.start() # Start z
sleep(600)
x.start() # Only start x when 10 minutes have past

最新更新