gpt4 book ai didi

python - 如何启动和停止周期性后台任务?

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:03 25 4
gpt4 key购买 nike

此应用程序需要能够在各种其他用户启动的任务之前和之后启动和停止定期心跳消息。使用@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)

最佳答案

看起来您需要调用这些方法:

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"

关于python - 如何启动和停止周期性后台任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47016888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com