python - APScheduler 执行后立即退出

标签 python apscheduler

我正在尝试为 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 的相应示例。

关于python - APScheduler 执行后立即退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42119673/

相关文章:

python - 每个月的第 n 天运行 APScheduler 作业

python - 我无法使用 django 连接到数据库

python - 将 pyspark 数据框中的周末日期移至上一个工作日

python - 如何在 Python 3 中获取列表中的列表编号?

python - 科学数据包 : Convert one-hot encoding to encoding with integers

python - Django Heroku APScheduler Scrapy

Python APScheduler 删除作业后抛出异常

python - Django 可重用应用程序 url 命名空间问题

Python APScheduler - AsyncIOScheduler 如何工作?

Python APScheduler 如何禁用日志记录