python的APScheduler框架,如何接收键盘信号停止运行


啥也不说了,先贴代码:


 def monitor(client):
    run_heartbeat = client.run.heartbeat
    etc_rpc = client.etc.rpc
    document = etc_rpc.find_one({'server':'taskmanager'})
    rpc = document['host'] + ':' + document['port']
    if process_ok('taskmanager'):
        run_heartbeat.update({'process':'taskmanager','rpc':rpc},{'$set':{'selftesttime':datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),'selftest':'ok'}}) 
        logging.info("update : selftest is 'ok'")
        print "update : run_heartbeat.taskmanager.selftest is 'ok'"
    else:
        run_heartbeat.update({'process':'taskmanager','rpc':rpc},{'$set':{'selftesttime':datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),'selftest':'process error'}}) 
        logging.info("update : selftest is 'process error'")
        print "update : run_heartbeat.taskmanager.selftest is 'process error'"

if __name__ == "__main__":
    print "TaskMonitor beginning......"
    sched = Scheduler()
    sched.daemonic = False
    sched.add_interval_job(monitor,seconds=int(tasktime),args=[client]) 
    sched.start()

功能:每隔tasktime秒就运行一次monitor函数
期望结果:在运行过程中通过CTRL+C停止
求大神解决办法!

python2.7

老挪威炸酱面 9 years, 9 months ago

直接给 sched.start() 加个 try... except ,如下:


 try:
    sched.start()
except (KeyboardInterrupt, SystemExit):
    sched.shutdown(wait=True)

上吊前微微笑 answered 9 years, 9 months ago

安装一个signal handler即可


 import signal, os


def handler(signum, frame):
    print "got signal", signum
    if signum == signal.SIGINT:
        print "got Ctrl +C , we will quit"
        os._exit(1)

signal.signal(signal.SIGINT, handler)

if __name__ == '__main__':
    import time
    while True:
        time.sleep(1)

小A真是欠草 answered 9 years, 9 months ago


 def handler(signum, frame):          #接收键盘信号
    #print 'catched interrupt signal!'
    print 'EXIT'
    sched.shutdown(False)

signal.signal(signal.SIGINT, handler)

if __name__ == "__main__":
    sched = Scheduler()
    sched.daemonic = False
    sched.add_interval_job(monitor,seconds=int(jobtime),args=[client]) 
    sched.start() 
    signal.pause()

这样就成功了,关键在signal.pause()不过我自己也还没搞懂为什么这样就可以。。。。

小小小小小纸团 answered 9 years, 9 months ago

Your Answer