如何启动和停止定期后台任务?

时间:2017-10-30 13:48:51

标签: python scheduled-tasks

此应用程序需要能够在各种其他用户启动的任务之前和之后启动和停止定期心跳消息。以@ Matthew的Monitor class为例,在启动消息或指示正在发送消息时,没有定期打印Heartbeat message sent。也没有错误消息指示周期性任务尚未启动的原因 - 只是opStartHeartbeat和opStopHeartbeat的打印消息。缺少什么?

def opHeartbeat():
    ...
    zocket.send(opMsg)
    print "Heartbeat message sent"

class HeartbeatClass(object):
    def __init__(self):
        self.schedule = sched.scheduler(time.time, time.sleep)
        self._running = False

    def periodic(self, action, actionargs=()):
        if self._running:
            self.event = self.schedule.enter(HEARTBEAT_INTERVAL, 1, self.periodic, (action, actionargs))
            action(*actionargs)

    def start(self):
        self._running = True
        self.periodic(opHeartbeat)
        self.schedule.run()

    def stop(self):
        self._running = False
        if self.schedule and self.event:
            self.schedule.cancel(self.event)

heartbeat = HeartbeatClass()

def opStartHeartbeat():
    global HEARTBEAT_INTERVAL
    HEARTBEAT_INTERVAL = raw_input('Enter Heartbeat period: ')
    heartbeat.start()

def opStopHeartbeat():
    heartbeat.stop()
    print "   Heartbeat stopped"

def opMenuChoice(option):
   ...
   elif (option == 31):
      opStartHeartbeat()
   elif (option == 32):
      opStopHeartbeat()
   return

while (option != 99):
   option = raw_input('Enter menu option: ')
   opMenuChoice(option)

1 个答案:

答案 0 :(得分:1)

看起来您需要调用方法:

def opStartHeartbeat():
    global HEARTBEAT_INTERVAL
    HEARTBEAT_INTERVAL = raw_input('Enter Heartbeat period: ')
    heartbeat.start()  # Round brackets call the method

def opStopHeartbeat():
    heartbeat.stop()
    print "   Heartbeat stopped"