footonwonton
footonwonton

Reputation: 794

APScheduler exits immediately after execution

I am trying to contribute to a project on Github for collecting financial data.

The code..

    # 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()

The problem is, once the script is executed it runs for a split second then stops, there are no traceback errors.

Is the function incorrectly called or am I missing some parts of code? The Communities help would be much appreciated!

Upvotes: 2

Views: 2843

Answers (1)

JoshAdel
JoshAdel

Reputation: 68702

The formal answer to your issue is that when using APScheduler v2, the default behavior of the scheduler is to run in threaded mode, which will return immediately after you apply the .start():

https://github.com/agronholm/apscheduler/blob/2.1/apscheduler/scheduler.py#L90-L91

Since it returns immediately and nothing keeps the main thread of your program alive, your program exits immediately. You need to keep your programming running long enough so that the scheduler can fire an event, or you need to run using a blocking version of the scheduler.

For this older version of APscheduler, you need to run in standalone mode if you want the scheduler to block:

https://github.com/agronholm/apscheduler/blob/2.1/examples/interval.py

or you if you want to continue running in threaded mode:

https://github.com/agronholm/apscheduler/blob/2.1/examples/threaded.py

Newer versions of APScheduler have separate BlockingScheduler andBackgroundScheduler` classes and you should consult the appropriate examples for the updated API.

Upvotes: 1

Related Questions