How To Add Time Delay in Python?The caller thread's execution can be suspended for any amount of time using the sleep() function in the time module. One million times is the default quantity of times it will execute your code. There are several ways to add a time delay in Python, including:
Approach 1: Using time.sleep() functionSteps:
Example code: Output: Approach 2: Using threading.Event. wait functionIn the approach of threading.Event.wait for function, thread suspends until the successful execution of the set() method is completed. It can take a parameter that can be used as a specific time, which means the execution will stop until the specified time has passed. Threading.Event.wait() is the syntax to be followed to use this approach to add a time delay in any code. Example: Output: Approach 3: Using threading.Timer classTimer objects represent tasks that need to start at a specified time. These things are set to run on a separate thread from the one that executes the action. Example: Output: Thread Timer javaTpoint Approach 4: Using the datetime moduleDate and time are not separate data types in Python, but they can be used together by importing the datetime package. Install the Python Datetime Module outside is not required outside because it is already included in Python. Classes for working with date and time are provided by the Python datetime module. Numerous capabilities to deal with dates, times, and time periods are provided by these classes.When working with date and datetime in Python, you're actually working with objects rather than strings or timestamps because the language recognizes date and datetime as things. For example: Output: Approach 5:Using Sched module in PythonThe Sched module, which serves as the industry standard library, can be used to build bots and other automation and monitoring programs. A general event scheduler for running jobs at certain times is implemented by the sched module. It offers tools comparable to task schedulers in Windows or Linux, but the key benefit is that platform differences may be ignored according to Python's own sched module. For example: Output: Starting... ...Finished These are examples of time delays in python. It's important to note that the time.sleep() function will cause the entire program to pause for the specified amount of time, while the datetime and sched examples will only delay the execution of a specific section of code. Next TopicHow to check nan in Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India