APScheduler:完成上一份工作后触发新工作

问题描述 投票:1回答:1

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

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

cron python-3.6 apscheduler
1个回答
3
投票

这可以使用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,逻辑会更简单。

© www.soinside.com 2019 - 2024. All rights reserved.