如何在python中创建一个间隔函数调用线程的后台?

The*_*ear 5 python heartbeat

我正在尝试实现在后台运行的心跳调用.如何创建一个每隔30秒的间隔调用的线程调用,调用以下函数:

self.mqConn.heartbeat_tick()
Run Code Online (Sandbox Code Playgroud)

我怎么能阻止这个线程?

非常感谢.

Eri*_*ric 7

使用包含循环的线程

from threading import Thread
import time

def background_task():
    while not background_task.cancelled:
        self.mqConn.heartbeat_tick()
        time.sleep(30)
background_task.cancelled = False

t = Thread(target=background_task)
t.start()

background_task.cancelled = True
Run Code Online (Sandbox Code Playgroud)

或者,您可以继承定时器,以便轻松取消:

from threading import Timer

class RepeatingTimer(Timer):
    def run(self):
        while not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
            self.finished.wait(self.interval)


t = RepeatingTimer(30.0, self.mqConn.heartbeat_tick)
t.start() # every 30 seconds, call heartbeat_tick

# later
t.cancel() # cancels execution
Run Code Online (Sandbox Code Playgroud)