P1ng3r
P1ng3r

Reputation: 45

Periodically execute function every n minutes while doing other stuffs

I want to basically update a variable value every 5 minutes by calling a function in python while doing other tasks if time is not 5 minutes. I tried to use strftime to keep time but got lost. Not sure what mistake I am making. Any help is much appreciated.

    variable = 0
    start_time = strftime("%M")
    While True:
        {do something here}
        current_time = strftime("%M")
        diff = int(start_time) - int(current_time)
        if diff is 5 minutes:
            function_call() #updates the variable
        else:
            Use the old variable value

Upvotes: 2

Views: 2524

Answers (1)

nico
nico

Reputation: 2121

  1. If you want to an asynchronous function call take a look at: Timer Objects and use them as such (from the docs):

    from threading import Timer
    t = Timer(300.0, function_call)
    t.start() # after 300 seconds, function_call will be called
    
  2. Otherwise the simpler solution (without threads) is just to check the difference from time calls as such (as you were trying to do):

    from time import time
    start_time = time()
    # do stuff
    if time() - start_time > 300: # 300 secs
        function_call()
    

So using the 2nd option your code could look like this:

from time import time
variable = 0
start_time = time()
While True:
    {do something here}
    current_time = time()
    diff = current_time - start_time
    if diff > 5*60:
        function_call() #updates the variable
        start_time = current_time
    else:
        Use the old variable value

Upvotes: 4

Related Questions