问题
I'm running a scheduler using python apscheduler inside web.py framework. The function runserver is supposed to run everyday at 9 a.m but it is inconsistent. It runs most days but skips a day once in a while.
Code:
import web
from apscheduler.schedulers.blocking import BlockingScheduler #Blocking Scheduler
#URLs
urls = (
'/startscheduler/','index',
)
Nightlysched = BlockingScheduler()
@Nightlysched.scheduled_job('cron', hour=9)
def runserver():
print 2+2 #doing some calculations here
#Main function to run the cron JOB
if __name__ == "__main__":
Nightlysched.start() #stating the job
app = web.application(urls, globals())
app.run()
What is the correct way to configure the scheduler to run every day at 9.a.m?
回答1:
APScheduler has a grace period during which jobs are allowed to run. If for some reason the scheduler is busy and/or the load of the host is too high, APScheduler might fail to start the job in time.
In this cases, the job will be discarded if it could not be started during the grace time (an explanatory message will be logged if you have initialized Python logging).
Depending on the actual root cause:
- If the scheduler failed to schedule the job in time, you can use
misfire_grace_time=None
to tell APScheduler to schedule the job as soon as it can instead of discarding it. - By default, only one instance of each job is allowed to be run at the same time. Make sure the previous run has finished. It is possible to set the maximum number of instances for a particular job that the scheduler will let run concurrently, by using the
max_instances
keyword argument when adding the job. In this case you also may need to usecoalesce=False
. Do this only if the job takes longer than 24 hours (in your case) and you accept that two instances of your job could be running simultaneously. - If there were too many jobs running, but the machine load wasn't too high, it means you have more jobs than what you can run concurrently. You can try increasing the size of the thread pool that APScheduler executor is using to run jobs (this depends on your setup, check: http://apscheduler.readthedocs.org/en/latest/userguide.html).
In summary, I'd first try with misfire_grace_period
:
@Nightlysched.scheduled_job('cron', hour=9, misfire_grace_time=None)
As a note, though, as @Alex mentioned I don't grasp why your code works, because the call to Nightlysched.start()
should be blocking and preventing your web application from running. I guess this is pasted code and doesn't really represent what you are running. To me, it looks like you should instead be using a non-blocking scheduler like BackgroundScheduler.
来源:https://stackoverflow.com/questions/34896705/python-apscheduler-not-consistent