Reputation: 45
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
Reputation: 2121
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
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