Python 如何启动和停止定期后台任务?
该应用程序需要能够在各种其他用户启动的任务之前和之后启动和停止周期性心跳消息。以@Matthew's为例,启动消息或指示消息正在发送时,没有周期性的Python 如何启动和停止定期后台任务?,python,scheduled-tasks,Python,Scheduled Tasks,该应用程序需要能够在各种其他用户启动的任务之前和之后启动和停止周期性心跳消息。以@Matthew's为例,启动消息或指示消息正在发送时,没有周期性的心跳消息发送。也没有错误消息指示周期性任务未启动的原因-只有opStartHeartbeat和OPSTOPPHEART的打印消息。少了什么 def opHeartbeat(): ... zocket.send(opMsg) print "Heartbeat message sent" class HeartbeatClass
心跳消息发送
。也没有错误消息指示周期性任务未启动的原因-只有opStartHeartbeat和OPSTOPPHEART的打印消息。少了什么
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)
看起来您需要调用以下方法:
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"