APScheduler how to trigger job now

霸气de小男生 提交于 2019-12-09 03:03:25

问题


I have an APScheduler in a Flask app, sending events at some intervals.

Now i need to "refresh" all jobs, in fact just starting them now if they don't run without touching on the defined interval.

I'v tried to call job.pause() then job.resume() and nothing, and using job. reschedule_job(...) would trigger it but also change the interval... which i don't want.

My actual code is bellow:

cron = GeventScheduler(daemon=True)
# Explicitly kick off the background thread
cron.start()

cron.add_job(_job_time, 'interval', seconds=5, id='_job_time')
cron.add_job(_job_forecast, 'interval', hours=1, id='_job_forecast_01')

@app.route("/refresh")
def refresh():
    refreshed = []
    for job in cron.get_jobs():
         job.pause()
         job.resume()
         refreshed.append(job.id)
    return json.dumps( {'number': len(cron.get_jobs()), 'list': refreshed} )

回答1:


You could just run the job function directly too.

for job in cron.get_jobs():
    job.func() 

If you had args or kwargs being passed into the function, you'd have to pull those out of job.args and/or job.kwargs. See apscheduler.job.Job




回答2:


I discourage from calling job.func() as proposed in the accepted answer. The scheduler wouldn't be made aware of the fact that job is running and will mess up with the regular scheduling logic.

Instead use the job's modify() function to set its next_run_time property to now():

for job in cron.get_jobs():
    job.modify(next_run_time=datetime.now())

Also refer to the actual implementation of class Job.




回答3:


As a workaround i've done using the following. In summary i cycle through all jobs cron.get_jobs() and create a one-time job using Job object to a 'date' trigger, which only trigger once, at datetime.now since not specified.

def refresh():
    refreshed = []
    for job in cron.get_jobs():
        cron.add_job(job.func, 'date', id='{0}.uniq'.format(job.id), max_instances=1)
        refreshed.append(job.id)
    return json.dumps( {'number': len(cron.get_jobs()), 'list': refreshed} )


来源:https://stackoverflow.com/questions/32230896/apscheduler-how-to-trigger-job-now

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!