如何进行不阻止的计划任务?

时间:2017-10-30 22:16:35

标签: python scheduled-tasks

Monitor class的这种修改需要能够在其他用户启动的任务之前和之后启动和停止定期消息。它当前能够启动定期消息但随后阻止,不允许用户启动另一个任务或正常停止自己(heartbeat.stop())。有没有办法解决这个问题,以便heartbeat.start()不会阻止?

def opHeartbeat():
    ...
    zocket.send(opMsg)

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():
    print "   Enter Heartbeat period in seconds or <enter> for 5s"
    global HEARTBEAT_INTERVAL
    HEARTBEAT_INTERVAL = raw_input('   Enter Heartbeat period: ')
    if HEARTBEAT_INTERVAL == (""):
        HEARTBEAT_INTERVAL = 5
    heartbeat.start()

def opStopHeartbeat():
    heartbeat.stop()

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

option = 0
GObject.threads_init()
while (option != 99):
   option = raw_input('Enter menu option: ')
   opMenuChoice(option)

1 个答案:

答案 0 :(得分:0)

使用apschedule lib BackgroundScheduler(感谢@Sraw)。