How to Make a Time Delay in Python

Created
Modified

Using time.sleep Function

This function actually suspends execution of the calling thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. See the following example:

#!/usr/bin/python3
# -*- coding: utf8 -*-

# Import module
import time

# def sleep(secs: float) -> None
time.sleep(0.5)
2022-04-27 10:48:46.195335
2022-04-27 02:48:46.195834+00:00

Using threading.Timer Objects

This class represents an action that should be run only after a certain amount of time has passed — a timer. Timer is a subclass of Thread and as such also functions as an example of creating custom threads. like this:

#!/usr/bin/python3
# -*- coding: utf8 -*-

# Import module
from threading import Timer

sec = 2

def hello(in_sec):
  print(f'function called {in_sec} s')

t = Timer(sec, hello, [sec])
# Start the thread's activity.
t.start()
function called 2 s

Timers are started, as with threads, by calling their start() method. It does not stop execution of the whole script (except for the function you pass it).

Related Tags

#make# #time# #delay#