I have a function F1 that loops continuously (while loop). I have set a condition, if met, calls another function F2 inside function F1. Once called, the function F2 shouldn't be called again for a few seconds, say 3 secs, even if the condition is met again within 3 seconds. But function F1 has to be looping continuously. How do I achieve it?
Asked
Active
Viewed 92 times
2
-
2can you share the code you already have? is time.sleep(3) not helping you? – Axblert Dec 27 '19 at 10:12
-
2@Axblert time.sleep() won't help because is freezes the script. – Psytho Dec 27 '19 at 10:14
-
ah interesting, it would freeze the entire script, not just the scope of the function? – Axblert Dec 27 '19 at 10:15
-
Maybe you can use timers : https://stackoverflow.com/questions/17167949/how-to-use-timer-in-c – WaLinke Dec 27 '19 at 10:35
3 Answers
4
Save time when you call F2 (say time_f2
). Next time the condition is met, compare now with time_f2
and call F2 only if the difference is more than 3 seconds.

Psytho
- 3,313
- 2
- 19
- 27
-
Scope of time_f2 is limited to F1's one instance only. Once F1 is called again, time_f2 will not have the same value as the previous run. It can be defined as Global variable. – Main Dec 27 '19 at 10:33
2
You can try something like below. I have introduced new parameters to F1. In <condition met>
you will write your own conditions.
from datetime import datetime
first_time_f2_call = True
time_f2_call = datetime.now()
while True:
time_f2_call = f1(first_time_f2_call, time_f2_call)
first_time_f2_call = False
def f1(first_f2_call, last_f2_call_time):
if first_f2_call:
time_diff = datetime.now() - datetime.now()
else:
time_diff = datetime.now() - last_f2_call_time
if <condition met> and time_diff.seconds > 3:
f2()
last_f2_call_time = datetime.now()
.
.
.
return last_f2_call_time

Main
- 150
- 1
- 10
2
Sure there are better ways, but you can use time.time() to watch for at least 3 seconds of difference and reset a flag
import time
tf = 0
ti = 0
while 1:
print('your_main_stuff()')
yourcondition = True
if yourcondition and tf==ti:
print('do_your_stuff_once_at_3_sec()')
count = True
ti = time.time()
if count:
tf = time.time()
if tf-ti>3:
tf = time.time()
ti = time.time()
count = False

Guinther Kovalski
- 1,629
- 1
- 7
- 15