Member-only story
Delay execution of code in Python the non-blocking way without using time.sleep()
In some cases we might want to delay execution of code and the first method we usually think of is time.sleep(). It is decent if the rest of the program is intended to be run after sleep() as they are relying on its result or the intention is to just pause the program for some breather. But, in some scenarios we might want to continue to run the program as the subsequent pieces of logic are independent or we have a mixture of waitable and non-waitable code to be executed.
threading.Timer()
threading.Timer() might be the method you’re looking for. It creates a thread hence non-blocking and delay the execution of a function by n seconds.
Instantiate Timer() class with 10 seconds delay in running the method callme() with args pass to the method.
t = Timer(10, callme, args=["hello"])
t.start()
Any code before t.join() will be executed immediately and the one after will be executed after the timer ends. This is handy when we have some…