我正在使用 APScheduler(3.5.3) 来运行三个不同的作业。我需要在完成第一份工作后立即触发第二份工作。另外我不知道第一份工作的完成时间。我将触发器类型设置为 cron 并计划每 2 小时运行一次。
我克服这个问题的一种方法是在每项工作结束时安排下一项工作。我们还有其他方法可以通过 APScheduler 实现吗?
最佳答案
这可以使用 scheduler events 来实现.查看这个改编自文档的简化示例(未经测试,但应该可以工作):
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,逻辑会更简单。
关于cron - APScheduler:完成上一个工作后触发新工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54996869/