View Single Post
Posts: 486 | Thanked: 251 times | Joined on Oct 2009
#15
Originally Posted by jolouis View Post
You can do it with your python script itself... just put your code into a loop that repeats forever, and at the end of the loop (just before you start again), put a nice long sleep in.
At the tiny cost of a little math, you can have the code run at relatively precise intervals instead of gradually drifting by the execution time of the code itself. You can execute immediately the first time by putting the sleep at the bottom of the loop, or always on the even time boundary by putting the sleep at the bottom.

This is so simple because of the properties of the modulo function and that days, hours, minutes, and seconds are all integer multiples of each other. Use something like 10, 15, or 60 instead of 300 if you don't want to wait 5 minutes. To run once an hour on the hour, use 3600. Add an offset before the last ")" in the sleep function to start at a fixed time after an even time boundary.
Code:
import time

while 1:
    # Now we wait for the next 5 minute boundary
    time.sleep(300 - time.time()%300)
    # Your python code goes here,
    # all the following lines are just an example
    t = time.time()
    ts = time.localtime(t)
    print t
    print ts
    print time.asctime(ts)