我有一个无限循环运行的代码,从外部源收集实时数据。
while True:
x = Livedata() # this should stop for 10 mins when x < 30, then restart.
y = Livedata()
z = Livedata()
我希望代码暂停收集数据N
分钟 当满足某个条件时,对于x
变量,例如x < 30
. 当x
挂起时,代码不应停止收集y
和z
的数据。N
分钟后,再次收集x
数据,直到再次满足条件。
我认为线程是最好的选择,但如果你想要一种无线程的方式,你可以使用类似time.time()
的东西来跟踪你想做的每件事的每个开始时刻。
如果x > 30
,这将始终运行x
代码,否则它会跳过x = liveData()
10 分钟。10 分钟后,它将重新启动。y
和z
只是做他们已经做过的事情。
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