1
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?

  • Do you want to execute that function every five minutes, or every five minutes _while inside that loop_? How long do you expect that loop to take? – tobias_k Aug 06 '14 at 19:45
  • What have you tried so far ? Do you want the method to wait 5 minutes and then do something or check that it has been 5 minutes since the last execution ? – El Bert Aug 06 '14 at 19:45
  • Do I understand you correct, that you want to execute this loop often, but the function should get called no more than once in 5 min? – bereal Aug 06 '14 at 19:46

3 Answers3

1

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
...
Community
  • 1
  • 1
tobias_k
  • 81,265
  • 12
  • 120
  • 179
0

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.

Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
0

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()
TheBlueMan
  • 316
  • 1
  • 4
  • 27