使用Timer类并在可调用中重新启动计时器,是Python中在后台运行周期性计时器的标准方法。
这有两个主要缺点:
- 它并不是真正周期性的:计时器的设置,...
- 它为每个周期创建一个新线程
是否有 Timer 类的替代方案? sched类我看了一下,但是在MainThread中运行会阻塞,不建议在多线程环境中运行。
如何在 python 中使用高频周期性计时器(100 毫秒周期),例如在收集批量数据发送到数据库时定期清空文档队列?
最佳答案
我想出了以下替代方案:
import threading
import time
class PeriodicThread(StoppableThread):
'''Similar to a Timer(), but uses only one thread, stops cleanly and exits when the main thread exits'''
def __init__ (self, period, callable, *args, **kwargs):
super(PeriodicThread, self).__init__()
self.period = period
self.args = args
self.callable = callable
self.kwargs = kwargs
self.daemon = True
def run(self):
while not self.stopped():
self.callable(*self.args, **self.kwargs)
time.sleep(self.period)
关于python - python中的周期性定时器,周期较小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14505478/