繁体   English   中英

APscheduler不会停止

[英]APscheduler will not stop

我有一个正在为网站开发的python代码,除其他外,该网站创建一个excel工作表,然后将其转换为json文件。 我需要该代码连续运行,除非它被网站管理员杀死。

为此,我正在使用APscheduler。

该代码可以在没有APscheduler的情况下完美运行,但是当我尝试添加其余代码时,会发生以下两种情况之一: 1)它永远运行,即使使用“ ctrl + C”也不会停止,我需要使用任务管理器将其停止,或者2)它只运行一次,然后停止

不会停止的代码:

from apscheduler.scheduler import Scheduler
import logging
import time

logging.basicConfig()
sched = Scheduler()
sched.start()

(...)
code to make excel sheet and json file
(...)

@sched.interval_schedule(seconds = 15)
def job():
    excelapi_final()

while True:
    time.sleep(10)
sched.shutdown(wait=False)

一段时间后停止运行的代码:

from apscheduler.scheduler import Scheduler
import logging
import time

logging.basicConfig()
sched = Scheduler()

(...)
#create excel sheet and json file
(...)

@sched.interval_schedule(seconds = 15)
def job():
    excelapi_final()
sched.start()

while True:
    time.sleep(10)
    sched.shutdown(wait=False)

我从其他问题,一些教程和sched.shutdown的文档中sched.shutdown应该允许ctrl + C杀死代码-但是这是行不通的。 有任何想法吗? 提前致谢!

您可以使用独立模式:

sched = Scheduler(standalone=True)

然后像这样启动调度程序:

try:
    sched.start()
except (KeyboardInterrupt):
    logger.debug('Got SIGTERM! Terminating...')

您更正后的代码应如下所示:

from apscheduler.scheduler import Scheduler
import logging
import time

logging.basicConfig()
sched = Scheduler(standalone=True)

(...)
code to make excel sheet and json file
(...)

@sched.interval_schedule(seconds = 15)
def job():
    excelapi_final()

try:
    sched.start()
except (KeyboardInterrupt):
    logger.debug('Got SIGTERM! Terminating...')

这样,当按Ctrl-C时程序将停止

您可以正常关闭它:

import signal
from apscheduler.scheduler import Scheduler
import logging
import time

logging.basicConfig()
sched = Scheduler()

(...)
#create excel sheet and json file
(...)

@sched.interval_schedule(seconds = 15)
def job():
    excelapi_final()

sched.start()

def gracefully_exit(signum, frame):
    print('Stopping...')
    sched.shutdown()

signal.signal(signal.SIGINT, gracefully_exit)
signal.signal(signal.SIGTERM, gracefully_exit)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM