APScheduler how to trigger job now

dashie picture dashie · Aug 26, 2015 · Viewed 11.3k times · Source

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} )

Answer

Lars Blumberg picture Lars Blumberg · Aug 16, 2017

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.