Python sleep() Function
While composing Python code, there might be times when you need to pause the program's execution for a specific amount of time. This is where the sleep() function proves to be useful.
The sleep() method pauses (waits) the current thread's execution for a specified period of time.
Python contains a time module that offers a number of helpful functions to manage time-related tasks. sleep() is one of the common activities among them. To stop the running of the program for a certain amount of time in seconds, we can use the sleep() function in Python. Keep in mind that the Python time sleep function only halts the current thread's execution, not the entire program.
The syntax of the sleep() function is direct. This is how sleep() function is used:
The sleep() function requires one parameter: seconds. This parameter determines the number of seconds to pause the program's execution. The seconds parameter can be a drifting point number, meaning you can pause the program's execution for parts of a second too.
Python sleep() Function Example:
" Printed time immediately " is printed Suspends (Delays) execution for 2.5 seconds. " Printed after 2.5 seconds" is printed ".
The aforementioned example demonstrates that sleep() accepts a floating-point integer as an input. Prior to Python 3.5, the suspension time could actually be shorter than the value supplied as an argument to the time() method.
The suspension period is at least the set number of seconds starting with Python 3.5. The core developers of Python 3.5 made a little adjustment to the way time.sleep() behaves. Even though the sleep is stopped by a signal, the newer Python sleep() system will continue for at least the amount of seconds we've chosen. However, if the message itself produces an exception, then this does not apply.
Example 2: Creating a Digital Clock
02:10:50 PM 02:10:51 PM 02:10:52 PM 02:10:53 PM 02:10:54 PM
Within the endless while loop of the programme shown above, we computed and reported the current local time. The program then waits for a full second. The current local time is once more calculated and printed. This procedure continues.
Timing and Delays with sleep(): Examples and Use Cases
There are numerous circumstances where you might need to utilize the sleep() function to bring delays into your program. The following are a couple of examples:
1. Delaying the Execution of a Function
Assume you have a function that you need to execute like clockwork. You can utilize the sleep() function to present a deferral between function calls. Here is an example:
Pauses the program execution for 10 seconds.
In this example, we characterise a function called func() that we need to execute like clockwork. We then, at that point, utilise some time circle to more than once call the function and pause the program's execution for 10 seconds utilising the sleep() function.
3. Adding a Delay Between Network Requests
Assume you have a program that makes network requests to a Programming interface. Assuming that you make such a large number of requests excessively fast, you might overpower the server and prompt it to crash. To forestall this, you can utilize the sleep() function to present a delay between network requests.
Pauses the program execution for 5 seconds
In this example, we utilize the requests library to make a network solicitation to a Programming interface. We then, at that point, process the reaction and pause the program's execution for 5 seconds utilizing the sleep() function.
3. Handling Interrupts and Exceptions with sleep()
One thing to remember while utilizing the sleep() function is that it tends to be interrupted by specific signals, for example, keyboard interrupts (CTRL-C on most frameworks). In the event that a keyboard interrupt happens while the program is sleeping, the program will be interrupted and may not continue true to form. To handle interrupts and exceptions with the sleep() function, you can utilize a try/except block.
In this example, we utilize a try/except block to catch a KeyboardInterrupt exception that could happen assuming that the client presses CTRL-C while the program is sleeping. On the off chance that a keyboard interrupt is distinguished, the program will print a message and exits.
Multithreading in Python:
Let's speak about groups and thread first before discussing sleep() in multithreaded systems. There are further instances in which we would want to provide a thread a Python sleep() function. Maybe we're using a production database containing millions of documents and a migration script.
We choose to use threads because we would not want to create any downtime but we really do not want to wait any longer than required for the migration to be finished.
Each instruction in a computer programme is a separate unit. The carrying out of those directives constitutes a procedure. A part of the process is called a thread. One or even more threads may be present in a process.
Example 1: Python Multithreading
Here is an instance of a Python programme with several threads.
Hola Hola Hey Hola Hey Hey
The above code has two threads, th1 and th2. The statements th1.start() and th2.start() are used to start these threads. Keep in mind that th1 and th2 may run concurrently and produce different results.
Example 2: time.sleep() in Python Multithreaded Programs
0 100 >>> 1 2 3 4 5 101 6 7 8 9 10 102
Choices to sleep() for Time sensitive Activities in Python
While the sleep() function is helpful for bringing delays into your program's execution, it may not be the best answer forever based tasks. The following are a couple of choices to consider:
The sched module gives a universally useful occasion scheduler for running functions at indicated times.
The Clock class in the stringing module permits you to schedule the execution of a function after a predefined delay.
The sleep() function in the asyncio library gives comparable functionality to sleep(), yet in an offbeat and non-blocking way.
In conclusion, the sleep() function is a helpful tool for bringing delays into your Python program's execution. It permits you to pause the program's execution for a predetermined number of seconds, and can be utilized in different circumstances, for example, delaying the execution of a function or adding a delay between network requests.
While utilizing the sleep() function, it's essential to handle interrupts and exceptions with a try/except block to keep the program from crashing startlingly. Also, you ought to think about involving elective libraries for more complicated simultaneousness and timing prerequisites. Generally, the sleep() function is an important tool for any Python developer to have in their toolkit.
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week