3

我正在使用 APScheduler(3.5.3) 运行三个不同的作业。我需要在第一份工作完成后立即触发第二份工作。另外我不知道第一份工作的完成时间。我已将触发器类型设置为 cron 并计划每 2 小时运行一次。

我克服这个问题的一种方法是在每个作业结束时安排下一个作业。我们有没有其他方法可以通过 APScheduler 来实现它?

4

1 回答 1

6

这可以使用调度程序事件来实现。查看改编自文档的简化示例(未经测试,但应该可以):

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,则逻辑会更简单。

于 2019-03-16T09:22:50.593 回答