我需要从列表中快速,准确地发送重复信息。 一个列表需要每100ms发送消息时,用+/- 10ms的窗口。 我试着用下面的代码,但问题是,定时器等待100毫秒,然后将所有的计算需要做,使计时器掉出可接受的窗口。
简单地减少等待已是一片狼藉,和不可靠的黑客。 在有围绕在循环过程中的列表进行编辑的事件的消息循环的锁。
如何让蟒蛇始终围绕发送邮件100ms的思考? 谢谢
from threading import Timer
from threading import Lock
class RepeatingTimer(object):
def __init__(self,interval, function, *args, **kwargs):
super(RepeatingTimer, self).__init__()
self.args = args
self.kwargs = kwargs
self.function = function
self.interval = interval
self.start()
def start(self):
self.callback()
def stop(self):
self.interval = False
def callback(self):
if self.interval:
self.function(*self.args, **self.kwargs)
Timer(self.interval, self.callback, ).start()
def loop(messageList):
listLock.acquire()
for m in messageList:
writeFunction(m)
listLock.release()
MESSAGE_LIST = [] #Imagine this is populated with the messages
listLock = Lock()
rt = RepeatingTimer(0.1,loop,MESSAGE_LIST)
#Do other stuff after this
我不明白,WRITEFUNCTION会造成一些延迟,但不超过允许的10毫秒以上。 我基本上是需要调用函数每100ms每个消息。 该MessageList中是小的,通常比元件较少。
接下来的挑战是与每10毫秒,1毫秒+/-这项工作:P
Yes, the simple waiting is messy and there are better alternatives.
First off, you need a high-precision timer in Python. There are a few alternatives and depending on your OS, you might want to choose the most accurate one.
Second, you must be aware of the basics preemptive multitasking and understand that there is no high-precision sleep
function, and that its actual resolution will differ from OS to OS too. For example, if we're talking Windows, the minimal sleep interval might be around 10-13 ms.
And third, remember that it's always possible to wait for a very accurate interval of time (assuming you have a high-resolution timer), but with a trade-off of high CPU load. The technique is called busy waiting:
while(True):
if time.clock() == something:
break
So, the actual solution is to create a hybrid timer. It will use the regular sleep
function to wait the main bulk of the interval, and then it'll start probing the high-precision timer in the loop, while doing the sleep(0)
trick. Sleep(0)
will (depending on the platform) wait the least possible amount of time, releasing the rest of the remaining time slice to other processes and switching the CPU context. Here is a relevant discussion.
The idea is thoroughly described in the Ryan Geiss's Timing in Win32 article. It's in C and for Windows API, but the basic principles apply here as well.
存储的开始时间。 发送邮件。 获取结束时间。 计算timeTaken =结束启动。 转换为FP秒。 睡眠(0.1-timeTaken)。 环回。
试试这个:
#!/usr/bin/python
import time; # This is required to include time module.
from threading import Timer
def hello(start, interval, count):
ticks = time.time()
t = Timer(interval - (ticks-start-count*interval), hello, [start, interval, count+1])
t.start()
print "Number of ticks since 12:00am, January 1, 1970:", ticks, " #", count
dt = 1.25 # interval in sec
t = Timer(dt, hello, [round(time.time()), dt, 0]) # start over at full second, round only for testing here
t.start()