在python中运行计时器几分钟 [英] Running a timer for few minutes in python
问题描述
我试图每秒运行某个函数"foo".我必须这样做几分钟(比如说5).
I am trying to run a certain function "foo" every second. I have to do this for a few minutes (say 5).
函数foo()向服务器发出100个HTTP请求(其中包含JSON对象),并打印JSON响应.
The function foo() makes 100 HTTP Requests (which contains a JSON object) to the server and prints the JSON response.
简而言之,我必须在5分钟内每秒发出100个HTTP请求.
In short, I have to make 100 HTTP requests per second for 5 minutes.
我刚刚开始学习python,因此没有广泛的知识.这是我尝试过的:
I have just started learning python, thus don't have extensive knowledge. This is what I have tried:
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次,但远远不止于此. 我也尝试过设置锁:
Due to multiple threads, the function foo isn't called 300 times but much much more than that. I have tried setting a lock too:
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()
其他代码段与先前的代码段相同.但这也行不通.
Rest of code is same as the previous code snippet. But this also does not work.
我该怎么做?
不同的方法
我尝试了这种对我有用的方法:
I have tried this approach which worked for me:
def foo():
noOfSecondsPassed = 0
while noOfSecondsPassed < 300:
#Code to make 100 HTTP requests
noOfSecondsPassed +=1
time.sleep(1.0)
foo()
这样做有什么缺点吗?
推荐答案
我会使用另一种更容易的方法.
I would use another approach which is easier I think.
创建300个计时器线程,每个计时器线程在前一个之后运行1秒.主循环几乎在瞬间执行,因此错误系数非常低. 这是一个示例演示:
Create 300 timer thread, each running 1 sec after the previous. The main loop is executed in almost an instant so the error factor is very low. Here's a sample Demo:
import datetime
import thread
import threading
def foo():
print datetime.datetime.now()
print threading.active_count()
for x in range(0,300):
t = threading.Timer(x + 1, foo)
t.start()
此代码输出应如下所示:
This code output should look like this:
2012-10-01 13:21:07.328029
301
2012-10-01 13:21:08.328281
300
2012-10-01 13:21:09.328449
299
2012-10-01 13:21:10.328615
298
2012-10-01 13:21:11.328768
297
2012-10-01 13:21:12.329006
296
2012-10-01 13:21:13.329289
295
2012-10-01 13:21:14.329369
294
2012-10-01 13:21:15.329580
293
2012-10-01 13:21:16.329793
292
2012-10-01 13:21:17.329958
291
2012-10-01 13:21:18.330138
290
2012-10-01 13:21:19.330300
289
...
如您所见,每个线程在前一个线程之后大约1秒钟启动,您正好启动了300个线程.
As you can see, each thread is launched about 1 sec after the previous and you are starting exactly 300 threads.
这篇关于在python中运行计时器几分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!