APScheduler:Trigger New job after completion of previous job

我只是一个虾纸丫 提交于 2021-02-07 22:38:41

问题


I'm using APScheduler(3.5.3) to run three different jobs. I need to trigger the second job immediately after the completion of first job. Also I don't know the completion time of first job.I have set trigger type as cron and scheduled to run every 2 hours.

One way I overcame this is by scheduling the next job at the end of each job. Is there any other way we can achieve it through APScheduler?


回答1:


This can be achieved using scheduler events. Check out this simplified example adapted from the documentation (not tested, but should work):

def execution_listener(event):
    if event.exception:
        print('The job crashed')
    else:
        print('The job executed successfully')
        # check that the executed job is the first job
        job = scheduler.get_job(event.job_id)
        if job.name == 'first_job':
            print('Running the second job')
            # lookup the second job (assuming it's a scheduled job)
            jobs = scheduler.get_jobs()
            second_job = next((j for j in jobs if j.name == 'second_job'), None)
            if second_job:
                # run the second job immediately
                second_job.modify(next_run_time=datetime.datetime.utcnow())
            else:
                # job not scheduled, add it and run now
                scheduler.add_job(second_job_func, args=(...), kwargs={...},
                                  name='second_job')

scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)

This assumes you don't know jobs' IDs, but identify them by names. If you know the IDs, the logic would be simpler.



来源:https://stackoverflow.com/questions/54996869/apschedulertrigger-new-job-after-completion-of-previous-job

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