Use scheduling module to run at specific times

I am working on a python script that should work between two given times. I have to use the sched build sched , as this script should be able to run directly on any machine with python 2.7 to reduce configuration time. (SO CRON NOT OPTION)

Several variables determine the parameters to start, here set_timer_start=0600 and set_timer_end=0900 are written in HHMM . I can stop the script at the right time.

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

Can someone give me an example (or link) on how to use the scheduler and possibly calculate the next execution date / time?

+6
source share
1 answer

If I understand your requirements correctly, then you probably need a loop that will re-enter the task in the queue every time it is completed. Sort 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 may be sufficient, for example, a basic implementation would look like this:

 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. 

NTN!

+9
source

Source: https://habr.com/ru/post/903194/


All Articles