matches = []
done = []
for item in matches:
dofunctioneveryloop()
done.extent(item)
dofunctiononce5min()
How can I execute dofunctiononce5min() inside this loop once 5 minute? This is backup to file function is this possible?
matches = []
done = []
for item in matches:
dofunctioneveryloop()
done.extent(item)
dofunctiononce5min()
How can I execute dofunctiononce5min() inside this loop once 5 minute? This is backup to file function is this possible?
Not sure I understood the question. I'll assume that you want this function to be executed only once every five minutes, no matter how often it is really called.
This might be overkill, but why not use a decorator? This will create a new function for the 'decorated' function that will execute the original function if X seconds have passed since the last execution. This will make sure the function is not executed more than once every 5 minutes (or whateer time interval in seconds you pass to the decorator), no matter whether it's called in that loop or elsewhere.
import time
def onceEveryXSeconds(seconds): # this creates the decorator
def wrapper(f): # decorator for given 'seconds'
f.last_execution = 0 # memorize last execution time
def decorated(*args, **kwargs): # the 'decorated' function
if f.last_execution < time.time() - seconds:
f.last_execution = time.time()
return f(*args, **kwargs)
return decorated
return wrapper
Usage:
@onceEveryXSeconds(3)
def function(foo):
print foo
while True:
print "loop"
function("Hello again")
time.sleep(1)
Output, with @onceEveryXSeconds(3)
loop
Hello again
loop
loop
loop
Hello again
loop
...
It is not recommended that you do this way. Perhaps the best approach could be to schedule it on operation system, and it run it task periodically.
Anyway, if want to run a statement every x time, here is an example
import time
for i in range(5):
print i
time.sleep(3) # seconds
Time as parameter should be fractioned like 0.5 seconds.
Assuming the loop takes longer than five minutes, you could use time.time() to determine when 5 minutes has been up.
import time
matches = []
done = []
starttime = time.time()
for item in matches:
dofunctioneveryloop()
done.extent(item)
if time.time() - starttime > 300:
dofunctiononce5min()
starttime = time.time()