Threading.timer间隔随机

时间:2015-08-04 23:58:05

标签: python multithreading timer

我最终试图让多个threading.timer线程以不同的等待时间运行,但我甚至无法根据单个变量获得一个线程来正常运行。

我添加了一些线来尝试消除处理时间漂移,但我仍然没有得到可预测的结果。当我运行这个脚本时:

import threading
import datetime
import time

def foo():
    print datetime.datetime.now()

print datetime.datetime.now()

iterations = 10

wait = 1

thread = None

next_call = time.time()

while iterations > 0:
    if thread == None or thread.is_alive() == False:
        next_call = next_call + wait
        thread = threading.Timer(next_call - time.time(), foo)
        thread.start()
        iterations -= 1

我得到了这个输出:

2015-08-04 16:46:17.606658
2015-08-04 16:46:18.656710
2015-08-04 16:46:19.607990
2015-08-04 16:46:20.654599
2015-08-04 16:46:21.626649
2015-08-04 16:46:22.753762
2015-08-04 16:46:23.610284
2015-08-04 16:46:24.729185
2015-08-04 16:46:25.609802
2015-08-04 16:46:26.608769
2015-08-04 16:46:27.610249

在计时器功能等待的时间内,其具有看似随机的不确定模式。有什么方法可以确定函数会等待正确的时间吗?

2 个答案:

答案 0 :(得分:0)

您可能想尝试其他一些机器/配置。

C:\bin\Python27\python.exe C:/www/wsgi/mysite/mysite/test.py
2015-08-04 20:24:36.491000
2015-08-04 20:24:37.492000
2015-08-04 20:24:38.491000
2015-08-04 20:24:39.491000
2015-08-04 20:24:40.491000
2015-08-04 20:24:41.491000
2015-08-04 20:24:42.491000
2015-08-04 20:24:43.491000
2015-08-04 20:24:44.491000
2015-08-04 20:24:45.491000
2015-08-04 20:24:46.491000

Process finished with exit code 0

那是Windows 7,PyCharm 4.5.1,python 2.7.9,全是64位

答案 1 :(得分:0)

如果您正在寻找每个线程之间的差异,这就是文档所要说的:

引自[Python 3](https://docs.python.org/3/library/threading.html#timer-objects

  

计时器在执行其操作之前等待的时间间隔可能不会   与用户指定的间隔完全相同。