执行带有条件 threading.Timer 的函数
Executing a function with threading.Timer with conditions
我想每 1 秒执行一次 getData
函数,仅进行 60 次迭代,然后我想执行 foo
函数。
def getDate():
q = client.getQuotes(['EURUSD'])
print q
我知道如何每 1 秒 运行 一次(使用 threading.Timer),但我找不到如何针对特定迭代执行此操作以及等待函数迭代是完成 timer.join()
这是一个如何做到这一点的例子:
import threading
import time
ITERATIONS = 60
# this could be any function
def afunc(t):
# the 't' argument is just to clarify the output
for i in range(2):
print('in timer #' + str(t) + ': ' + str(i))
time.sleep(0.2)
timers = []
for t in range(ITERATIONS):
# create a timer for this iteration (note the interval will be from 1.0 to the number of iterations)
ti = threading.Timer(1.0 + t, afunc, args=[t])
# save the timer in a list
timers.append(ti)
# start the timer
ti.start()
# wait for them all
for ti in timers:
ti.join()
print( 'all finished, call any other method here')
我想每 1 秒执行一次 getData
函数,仅进行 60 次迭代,然后我想执行 foo
函数。
def getDate():
q = client.getQuotes(['EURUSD'])
print q
我知道如何每 1 秒 运行 一次(使用 threading.Timer),但我找不到如何针对特定迭代执行此操作以及等待函数迭代是完成 timer.join()
这是一个如何做到这一点的例子:
import threading
import time
ITERATIONS = 60
# this could be any function
def afunc(t):
# the 't' argument is just to clarify the output
for i in range(2):
print('in timer #' + str(t) + ': ' + str(i))
time.sleep(0.2)
timers = []
for t in range(ITERATIONS):
# create a timer for this iteration (note the interval will be from 1.0 to the number of iterations)
ti = threading.Timer(1.0 + t, afunc, args=[t])
# save the timer in a list
timers.append(ti)
# start the timer
ti.start()
# wait for them all
for ti in timers:
ti.join()
print( 'all finished, call any other method here')