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

时间:2015-04-21 10:17:49

标签: python heartbeat

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

self.mqConn.heartbeat_tick()

另外我该如何阻止这个帖子?

非常感谢。

4 个答案:

答案 0 :(得分: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

或者,您可以将计时器子类化,以便轻松取消:

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

答案 1 :(得分:3)

快速跟进Eric的回答:您不能将Timer作为子类,因为它实际上是真正类的轻函数包装器:{{ 1}}。如果您这样做,我会收到this post中弹出的问题。

使用_Timer代替修复它:

_Timer

答案 2 :(得分:2)

执行此操作的一种方法是使用circuits应用程序框架,如下所示:

from circuits import Component, Event, Timer


class App(Component):

    def init(self, mqConn):
        self.mqConn = mqConn
        Timer(30, Event.create("heartbeat"), persist=True).register(self)

    def heartbeat(self):
        self.mqConn.heartbeat_tick()


App().run()

注意:我是电路的作者:)

这只是一个基本的想法和结构 - 您需要根据您的具体应用和要求进行调整!

答案 3 :(得分:1)

或者您可以在线程模块中使用Timer类:

from threading import Timer

def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
t.cancel() # cancels execution, this only works before the 30 seconds is elapsed

这不会每x秒启动一次,而是在x秒内延迟执行的线程。但你仍然可以把它放在循环中并使用t.is_alive()来查看它的状态。