APScheduler:触发上一个工作完成后的新工作 [英] APScheduler:Trigger New job after completion of previous job
问题描述
我正在使用APScheduler(3.5.3)运行三个不同的作业.我需要在完成第一份工作后立即触发第二份工作.另外我也不知道第一份工作的完成时间.我将触发器类型设置为cron,并计划每2小时运行一次.
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.
我克服这个问题的一种方法是在每个作业结束时安排下一个作业.我们还有其他方法可以通过APScheduler实现吗?
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?
推荐答案
这可以使用调度事件.请查看从文档改编的简化示例(未经测试,但应该可以使用):
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)
这假设您不知道工作的ID,但可以通过名称来识别它们.如果您知道ID,则逻辑会更简单.
This assumes you don't know jobs' IDs, but identify them by names. If you know the IDs, the logic would be simpler.
这篇关于APScheduler:触发上一个工作完成后的新工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!