我在Windows平台上使用Python,我需要每100毫秒或更低时间定期执行一段代码。举个例子:
while (packetNumber < 30000):
sock.sendto(bytes(MESSAGE, "utf-8"), (SERVER_IP, SERVER_PORT))
packetNumber = packetNumber + 1
print("Sent the", packetNumber, "th packet")
我只关心这一行的召唤时间:
sock.sendto(bytes(MESSAGE, "utf-8"), (SERVER_IP, SERVER_PORT))
并且需要每隔100毫秒(或尽可能准确)调用,例如:
11:24:07.00000
11:24:07.10000
11:24:07.20000
11:24:07.30000
等
实现这一目标的最准确方法是什么?
答案 0 :(得分:0)
这可能会对你有所帮助。你去do_something()每100ms调用一次。
此代码还证明了该方法在一秒钟内执行了10次。即它每100ms执行一次。见结果。
import threading
from time import time
def quit(delta):
print(delta)
return int(delta) == 1
def do_something(*args):
then = args[0]
now = time()
if quit(now - then):
threading.Timer(0.1, do_something, [then, quit]).cancel()
else:
threading.Timer(0.1, do_something, [then, quit]).start()
do_something(time())
结果:
0.10426497459411621
0.2058699131011963
0.3096139430999756
0.4199540615081787
0.525109052658081
0.6257798671722412
0.7308750152587891
0.8337719440460205
0.9371669292449951
1.041382074356079