【问题标题】:How to call a particular method in a background thread every X minutes in Python?如何在 Python 中每 X 分钟调用一次后台线程中的特定方法?
【发布时间】:2026-02-14 17:35:01
【问题描述】:

如何在 Python 中编写一个后台线程,它将每隔几分钟调用一个特定的方法。

比方说,如果我是第一次启动我的程序,那么它应该立即调用那个方法,然后它应该每隔 X 分钟继续调用那个方法?

可以用 Python 做吗?

我在 Python 线程方面没有太多经验。在 Java 中,我可以使用 TimerTaskScheduledExecutors 来解决这个问题,但不确定如何使用 Python 来解决?

在 Python 中执行此操作的最佳方法是什么?

【问题讨论】:

    标签: python multithreading background-thread


    【解决方案1】:

    使用threading.Timer

    例如:

    import threading
    
    def print_hello():
        print('Hello')
        timer = threading.Timer(2, print_hello) # # Call `print_hello` in 2 seconds.
        timer.start()
    
    print_hello()
    

    【讨论】:

    • 不知何故,当我运行上面的代码时,我看到 Hello 被打印了两次,每次 2 秒后,但之后什么都没有打印出来..
    • @SSH,对不起,我对 threading.Timer 的看法是错误的。它只运行该功能一次。我更新了答案。
    • 是的。现在它起作用了。最后一行使用time.sleep(100)有什么目的吗?
    • @SSH,啊..你不需要它。删除它。
    【解决方案2】:

    我认为如果不尝试使用Timer,这样做会容易得多。直接做:

    def my_background_task(seconds_between_calls):
        from time import sleep
        while keep_going:
            # do something
            sleep(seconds_between_calls)
    
    
    ...
    from threading import Thread
    t = Thread(target=my_background_task, args=(5*60,)) # every 5 minutes
    keep_going = True
    t.start()
    ...
    # and when the program ends
    keep_going = False
    t.join()
    

    【讨论】:

      【解决方案3】:

      我在这门课上运气不错。您可能希望在 time.sleep() 之前移动 self.func() 调用。

      import threading
      import time
      
      class PeriodicExecutor(threading.Thread):
      
          def __init__(self, sleep, func, *params):
              'Execute func(params) every "sleep" seconds'
              self.func = func
              self.params = params
              self.sleep = sleep
              threading.Thread.__init__(self, name = "PeriodicExecutor")
              self.setDaemon(True)
      
          def run(self):
              while True:
                  time.sleep(self.sleep)
      #           if self.func is None:
      #               sys.exit(0)
                  self.func(*self.params)
      

      【讨论】: