Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

cron - APScheduler:Trigger New job after completion of previous job

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...