1

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

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

可以用 Python 做吗?

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

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

4

3 回答 3

2

使用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()
于 2014-01-01T06:06:47.573 回答
0

我认为这很容易做到,而无需尝试使用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()
于 2014-01-01T06:15:44.153 回答
0

我在这门课上运气不错。您可能希望在 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)
于 2014-01-01T06:39:35.953 回答