dbader / schedule

Python job scheduling for humans.
https://schedule.readthedocs.io/
MIT License
11.71k stars 960 forks source link

Add run order for jobs when using a decorator to schedule a job. #539

Open jcphlux opened 2 years ago

jcphlux commented 2 years ago

This would be a nice add but I am adding my code here incase someone else wants a solution.

Add the ability to set the order of job set to run at the same time when using a decorator to schedule a job. I have solved this for myself using the below code.

Decorator

def func_order(order: int = 0):
    def decorator(f):
        f.order = order
        return f
    return decorator

Jobs

@func_order(2)
@repeat(every(1).minutes)
def job1():
     print('do job1')

@func_order(1)
@repeat(every(2).minutes)
def job2():
     print('do job2')

@repeat(every(2).minutes)
def job3():
     # order not set so will be last.
     print('do job3')

Main

from schedule import default_scheduler, idle_seconds, jobs

if __name__ == '__main__':
    while True:
        idle_sec = idle_seconds()
        if idle_sec is None:
            # No More Jobs.
            break
        elif idle_sec > 0:
            # This is to catch all functions that are close to the same time.
            idle_sec += 1
            time.sleep(idle_sec)

        runnable_jobs = list(filter(lambda job: job.should_run, jobs))
        if len(runnable_jobs) == 0:
            continue

        ordered_jobs = sorted(runnable_jobs, key=lambda job: job.job_func.func.order if hasattr(job.job_func.func, 'order') else 100000)
        for job in ordered_jobs:
            default_scheduler._run_job(job)