Use a thread containing a loop
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
Alternatively, you could subclass timer, to make cancelling easy:
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
heartbeat_tick()
takes a significant amount of time – Calfskin