使用带有条件的threading.Timer执行函数

时间:2018-09-26 14:14:00

标签: python python-2.7 python-multithreading

我只想每60迭代执行一次getData函数,之后再执行foo函数。

def getDate():
    q = client.getQuotes(['EURUSD'])
    print q

我知道如何每隔1秒钟运行一次(使用threading.Timer),但是我无法确定如何进行某些迭代并还要等待函数迭代完成timer.join()

1 个答案:

答案 0 :(得分:1)

以下是如何执行此操作的示例:

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')