我试图每秒运行一个特定的函数“foo”。我必须这样做几分钟(比如5)。
函数 foo() 向服务器发出 100 个 HTTP 请求(其中包含一个 JSON 对象)并打印 JSON 响应。
简而言之,我必须在 5 分钟内每秒发出 100 个 HTTP 请求。
我刚刚开始学习python,因此没有广泛的知识。这是我尝试过的:
import threading
noOfSecondsPassed = 0
def foo():
global noOfSecondsPassed
# piece of code which makes 100 HTTP requests (I use while loop)
noOfSecondsPassed += 1
while True:
if noOfSecondsPassed < (300) # 5 minutes
t = threading.Timer(1.0, foo)
t.start()
由于多线程,函数 foo 没有被调用 300 次,但远不止于此。我也尝试过设置锁:
def foo():
l = threading.Lock()
l.acquire()
global noOfSecondsPassed
# piece of code which makes 100 HTTP requests (I use while loop)
noOfSecondsPassed += 1
l.release()
其余代码与前面的代码片段相同。但这也行不通。
我该怎么做呢?
编辑:不同的方法
我已经尝试过这种对我有用的方法:
def foo():
noOfSecondsPassed = 0
while noOfSecondsPassed < 300:
#Code to make 100 HTTP requests
noOfSecondsPassed +=1
time.sleep(1.0)
foo()
这样做有什么坏处吗?