python毫秒级定时
时间: 2023-09-26 14:04:26 浏览: 110
要在Python中实现毫秒级的定时,可以使用下面这段代码:
```python
from time import sleep, time
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self.interval = interval
self.function = function
self.is_running = False
self.args = args
self.kwargs = kwargs
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
start = int(time() * 1000)
i = 0
if not self.is_running:
self.is_running = True
while True:
if not self.is_running:
break
i += 1
now = int(time() * 1000)
sleep_ms = i * self.interval - (now - start)
if sleep_ms < 0:
self.function(*self.args, **self.kwargs)
else:
sleep(sleep_ms / 1000.0)
self.function(*self.args, **self.kwargs)
def stop(self):
self.is_running = False
def hello(name):
print(f"[{time()}]\t Hello {name}!")
sleep(0.01)
print("starting...")
rt = RepeatedTimer(100, hello, "world")
try:
sleep(50)
finally:
rt.stop()
```
这段代码实现了一个名为`RepeatedTimer`的类,可以用来实现毫秒级的定时。你可以指定间隔时间(单位为毫秒),并提供要执行的函数及其参数。在上面的例子中,我们定义了一个`hello`函数来打印当前时间和一个问候语,并使用`RepeatedTimer`类创建了一个间隔100毫秒执行一次的定时器。在`try`块中,我们让程序休眠50秒钟,然后通过调用`stop()`方法停止定时器的执行。
参考链接:<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>
阅读全文