python - 在 python 中运行几分钟的计时器

标签 python multithreading timer python-multithreading

我试图每秒运行一个特定的函数“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()

这样做有什么缺点吗?

最佳答案

我会使用另一种我认为更容易的方法。

创建 300 个计时器线程,每个线程在前一个线程之后运行 1 秒。主循环几乎在瞬间执行,因此错误系数非常低。 这是一个示例演示:

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

此代码输出应如下所示:

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 个线程。

关于python - 在 python 中运行几分钟的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12672750/

相关文章:

java - 多线程写入文件时的行为

c++ - 如何在程序中设置 OpenMP 线程数?

javascript - jquery - 添加与 HTML div 关联的多个计时器

c# - 如何在 C# 中制作只显示秒和毫秒的秒表?

python - 根据词性分类的单词生成有意义的句子

python - chcp 65001 代码页导致程序终止而没有任何错误

java - 在 AWT 线程中运行代码

ios - 如何在 Swift 中的视频上叠加动态标签?

python - django 1.9 不为自定义用户模型创建表

来自 csv 的 Python 热图