问题
I am trying to contribute to a Python project on Github for collecting data from FXCM and I am having some problems with APScheduler inside a Class.
Below is a snipping of code.
# 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')
The Class is started with another script below:
# main.py
from director import TimeKeeper
if __name__ == "__main__":
"""
Description
"""
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 Class incorrectly designed or am I missing some parts of code? The Communities help would be much appreciated!
回答1:
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 and
BackgroundScheduler` classes and you should consult the appropriate examples for the updated API.
来源:https://stackoverflow.com/questions/42119673/apscheduler-inside-a-class-object