Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 506
Dinesh Avatar asked Oct 25 '25 04:10

Dinesh


1 Answers

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.

like image 82
Tomáš Linhart Avatar answered Oct 27 '25 01:10

Tomáš Linhart