Skip to main content
 首页 » 编程设计

python之APScheduler 执行后立即退出

2025年02月15日13think

我正在尝试为 Github 上的一个项目做出贡献,以收集财务信息 数据。

代码..

    # time_keeper.py 
 
    from apscheduler.scheduler import Scheduler   
 
 
    class TimeKeeper: 
        def __init__(self): 
            self.sched = Scheduler() 
 
        def queue_job(self): 
            print("message send to queue") 
 
        def start_timers(self): 
            self.sched.start() 
            self.sched.add_cron_job(self.queue_job, minute='0-59') 
 
 
    if __name__ == "__main__": 
        from time_keeper import TimeKeeper 
 
        TimeKeeper().start_timers() 

问题是,一旦执行脚本,它会运行一瞬间然后停止,没有回溯错误。

函数调用有误还是我遗漏了部分代码?非常感谢社区的帮助!

请您参考如下方法:

您的问题的正式答案是,当使用 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 和BackgroundScheduler` 类,您应该查阅更新 API 的相应示例。