我正在尝试为Github上的一个Python项目做贡献,以便从FXCM收集数据,我在一个类中遇到了一些APScheduler问题。
下面是一段代码。
# director.py
from apscheduler.scheduler import Scheduler
class Director(object):
"""
Description
"""
class TimeKeeper(Director):
"""
Description
"""
def __init__(self):
sched = Scheduler()
def min_1(self):
td = 300
tf = 'm1'
print("TimeDelta: %s --- Time Frame: %s --- Event: 'GetLive' sent to queue") % (td, tf)
# other functions at different times
def start_timers(self):
self.sched.start()
self.sched.add_cron_job(self.min_1, minute='0-59')
该类以下面的另一个脚本启动:
# main.py
from director import TimeKeeper
if __name__ == "__main__":
"""
Description
"""
TimeKeeper().start_timers()
问题是,一旦脚本执行,它会运行一瞬间然后停止,没有回溯错误。
类是否设计错误,或者我错过了部分代码?社区帮助将不胜感激!
答案 0 :(得分:1)
您的问题的正式答案是,在使用APScheduler v2时,调度程序的默认行为是以线程模式运行,在您应用.start()
后会立即返回:
https://github.com/agronholm/apscheduler/blob/2.1/apscheduler/scheduler.py#L90-L91
由于它立即返回并且没有任何东西使程序的主线程保持活动状态,因此程序会立即退出。您需要保持编程运行足够长的时间,以便调度程序可以触发事件,或者您需要使用调度程序的阻止版本运行。
对于此旧版本的APscheduler,如果您希望调度程序阻止,则需要以独立模式运行:
https://github.com/agronholm/apscheduler/blob/2.1/examples/interval.py
或者如果您想继续以线程模式运行:
https://github.com/agronholm/apscheduler/blob/2.1/examples/threaded.py
较新版本的APScheduler具有单独的BlockingScheduler and
BackgroundScheduler`类,您应查阅更新API的相应示例。