python - python中的周期性定时器,周期较小

标签 python timer

使用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/

相关文章:

python - 有条件地迭代 Pandas 中的列

python - python 中的面向对象设计。上下?

python - 比较运算符在 Python 与 C/C++ 中的优先级

timer - Fortran 内在计时例程,哪个更好? cpu_time 或 system_clock

java - 如何在Android应用程序中正确实现android.os.Handler类而不是Timer?

python - 如何在 Python 中使用计时器解锁条件?

python - PyQt5 和 Anaconda : ModuleNotFoundError: No module named 'PyQt5'

python - 如何获取多个字典值?

python时间一试除了

java - 定时器已取消