Python Forum

Full Version: python delay without interrupt the whole code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello.I have the following function:
from threading import Timer
a = 0
def TaskManager():
    global a
    t = Timer( 1, TaskManager )
    t.start()
    if(a == 5):
        t.cancel()
        return
    print("hello")
    a += 1
    

TaskManager()
I don't want to use time.sleep.
So, I want to pass a parameter in TaskManager function ,fox example I want to pass number 5, in order to wait for 5 seconds.
I tried to do this one:
from threading import Timer
def TaskManager(delay_time):
    
    t = Timer( 1 , TaskManager [delay_time])
    t.start()
    if(delay_time == 0):
        t.cancel()
        return
    print("hello")
    delay_time -= 1
    

TaskManager(5)
in order to delay for 5 sec. but I do not want interruption (like time.sleep() ).
I understand why the code is not working(because recursion never finishes)

I want to do something for a few seconds(for example) without interrupt the whole code like time.sleep().
I want something like millis() function from arduino( if you know).
How can I do this?
Thanks
It is very difficult to understand the purpose of the TaskManager() function. Obviously you want the program to print 'hello' now and then, but not too fast, with delays. Can you describe without code what you expect the program to do?
Let us know if this is what you are looking for:

from threading import Timer

breaker_breaker = False

def delayed_function (seconds_delayed) :
	global breaker_breaker
	breaker_breaker = True
	print (f'This funciton was delayed for {seconds_delayed} seconds.')

wait_for_it = Timer (3, delayed_function, '3')
wait_for_it.start ()

while breaker_breaker == False:
	print ('Still waiting...')
	for dummy in range (999999) : dummy =+ 1
Yes, this is what I want.Thank you very much!
This sort of solution would likely not work in a lot of other languages. Most compilers would be smart enough to realize that the for-loop body is constant (it always sets "dummy" to a constant +1), and also that there's no side effects, and would thus delete the loop entirely from the resulting executable.

I'd be a little worried, myself, that an infinite loop without any sort of time.sleep() would be very cruel to the processor. Even a tiny one, like time.sleep(0.0001) would be better than none at all.