Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use sched module to run at a given time

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?

like image 656
HTDutchy Avatar asked Dec 06 '11 13:12

HTDutchy


People also ask

How do I make Python functions run at a certain time?

Timer() to schedule function calls. However, if you want a particular function to wait for a specific time in Python, we can use the threading. Timer() method from the threading module. We'll show a simple example, which schedules a function call every 5 seconds.

How do I schedule a Python script to run daily?

Double-click on the Task Scheduler, and then choose the option to 'Create Basic Task…' Type a name for your task (you can also type a description if needed), and then press Next. For instance, let's name the task as: Run Hello World. Choose to start the task 'Daily' since we wish to run the Python script daily at 6am.


1 Answers

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!

like image 106
mac Avatar answered Sep 18 '22 20:09

mac