Use sched module to run at a given time

后端 未结 1 677
小鲜肉
小鲜肉 2020-12-30 13:49

I\'m working on a python script that needs to run between two given times. I\'m required to use the build in sched module as this script needs to be able to run

相关标签:
1条回答
  • 2020-12-30 14:11

    If I got your requirements right, what you need is probably a loop, that will re-enter a task in the queue every time it will be executed. Something along the lines of:

    # This code assumes you have created a function called "func" 
    # that returns the time at which the next execution should happen.
    s = sched.scheduler(time.time, time.sleep)
    while True:
        if not s.queue():  # Return True if there are no events scheduled
            time_next_run = func()
            s.enterabs(time_next_run, 1, <task_to_schedule_here>, <args_for_the_task>)
        else:
            time.sleep(1800)  # Minimum interval between task executions
    

    However, using the scheduler is - IMO - overkilling. Using datetime objects could suffice, for example a basic implementation would look like:

    from datetime import datetime as dt
    while True:
        if dt.now().hour in range(start, stop):  #start, stop are integers (eg: 6, 9)
            # call to your scheduled task goes here
            time.sleep(60)  # Minimum interval between task executions
        else:
            time.sleep(10)  # The else clause is not necessary but would prevent the program to keep the CPU busy.
    

    HTH!

    0 讨论(0)
提交回复
热议问题