pythonpython-decoratorsschedule

In python's module schedule, how can I print next run time once after job run?


After I run pending jobs with Python's schedule module, I'd like to print once next job scheduled at {next_job_time}.

This code prints the message every second which isn't what I want:

import schedule
import time

def Job():
    #doing something...

schedule.every(1).hours.do(Job)

while True:
    schedule.run_pending()
    print(f"next job scheduled at {schedule.next_run()}")
    time.sleep(1)

I thought about using a decorator around Job, that prints the message right after job is executed, but when I do this the time printed is that of the current execution and not the next one. I think this because decorators do their stuff before schedule marks the job as completed and updates the jobs list.

Any idea how I can print my message once right after a job completes and still get the correct next_run time?


Solution

  • I also found using the decorator seems to produce odd results, so I turn into the loop and display the next run there. The key is compare this 'next run' with the one we displayed the last time and only display if they differ.

    #!/usr/bin/env python3
    import time
    
    import schedule
    
    
    def job():
        print("job")
    
    
    def job2():
        print("job2")
    
    
    last = None
    schedule.every(10).seconds.do(job)
    schedule.every(7).seconds.do(job2)
    
    while True:
        schedule.run_pending()
    
        # Display next run, without repeat
        next_run = schedule.next_run()
        if next_run != last:
            print(f"Next run: {next_run}")
        last = next_run
    
        time.sleep(1)
    

    Sample output:

    Next run: 2024-03-02 06:32:37.449988
    job2
    Next run: 2024-03-02 06:32:40.449978
    job
    Next run: 2024-03-02 06:32:44.478158
    job2
    Next run: 2024-03-02 06:32:50.486706
    job
    Next run: 2024-03-02 06:32:51.499801
    job2
    Next run: 2024-03-02 06:32:58.520998
    job2
    Next run: 2024-03-02 06:33:00.518501