Python中的周期性定时器,周期较小

2 投票
1 回答
1603 浏览
提问于 2025-04-17 13:32

在Python中,使用Timer类并在可调用的地方重启定时器,是在后台运行定时器的标准方法。

不过,这种方法有两个主要缺点:

  • 它并不是真正的定时:设置定时器等过程会影响时间的准确性。
  • 每个周期都会创建一个新的线程。

有没有其他可以替代Timer类的方法呢?我看过sched类,但在主线程中运行会导致阻塞,而且在多线程环境中运行也不太推荐。

我该如何在Python中实现一个高频率的定时器(比如每100毫秒一次),例如在收集大量数据并准备发送到数据库时,定期清空一个文档队列?

1 个回答

4

我想出了以下一种替代方案:

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)

撰写回答