Use sched module to run at a given time

2019-02-05 02:29发布

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 directly on any machine that has python 2.7 as to reduce configuration time. (SO CRON IS NOT AN OPTION)

A few variables define the settings for the time to run, here set_timer_start=0600 and set_timer_end=0900 are written in HHMM. I'm able to stop the script at the right time.

I don't know exactly how sched works (the python doc page doesn't make to much sense to me), but as far as I understand It runs at a date/time (epoch) while I only want it to run at a given time (HHMM).

Can anyone give me an example (or link) on how to use the scheduler and perhaps calculate the next run date/time?

1条回答
贪生不怕死
2楼-- · 2019-02-05 03:27

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!

查看更多
登录 后发表回答