Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - loop at exact time intervals

I want to run a piece of code at exact time intervals (of the order of 15 seconds) Initially I used time.sleep(), but then the problem is the code takes a second or so to run, so it will get out of sync.

I wrote this, which I feel is untidy because I don't like using while loops. Is there a better way?

import datetime as dt
import numpy as np

iterations = 100
tstep = dt.timedelta(seconds=5)
for i in np.arange(iterations):
    startTime = dt.datetime.now()
    myfunction(doesloadsofcoolthings)
    while dt.datetime.now() < startTime + tstep:
        1==1
like image 551
AndyMoore Avatar asked Dec 19 '22 05:12

AndyMoore


1 Answers

Ideally one would use threading to accomplish this. You can do something like

import threading
interval = 15

def myPeriodicFunction():
    print "This loops on a timer every %d seconds" % interval

def startTimer():
    threading.Timer(interval, startTimer).start()
    myPeriodicFunction()

then you can just call

startTimer()

in order to start the looping timer.

like image 133
Jon Deaton Avatar answered Mar 31 '23 23:03

Jon Deaton