Python sleep (): How to add latency to Part II (Translated)

Tram Ho

Part I of the article:

Adding a Python sleep() Call With Decorators

There are times when you need to retry a faulty function. A common case is when downloading files when the server is busy. You often don’t want to send requests to the server too often, so adding a sleep() call between requests is essential.

Another situation I’ve experienced myself is when I need to check the status of a UI during an automated test session. The UI may load faster or slower than usual, depending on the computer you are running the test on. This can change what appears on the screen at the time the program authenticates something.

In this case, I can let the program sleep for a while and check everything awake a second or two later. Successful or unsuccessful tests run in these sleepy moments.

You can use decorator to add sleep() calls in these cases. If you are unfamiliar with decorators or you want to improve your knowledge, see the Primer on Python Decorators tutorial. See the following example:

sleep() is your decorator. It takes a timeout value and the number of times it should retry – the default is 3. In sleep() is another function, the_real_decorator() , which accepts the decorated function.

Finally, the function in the same wrapper() takes the arguments and keyword arguments that you pass into the decorated function. This is where magic appears! You use the while loop to retry the function call. If there are exceptions, call time.sleep() , increase the count of retries and run the function again.

Now, rewrite uptime_bot() to use your new decorator:

Here, you decorate uptime_bot() with the command sleep() 3 seconds. You have also removed the initial while loop as well as a call to sleep(60) . Decorator will take care of this from now on.

Another change you’ve made is to add a raise statement within the exception handler blocks. This ensures the decorator will work properly. You can write decorators to handle these errors, but because exceptions only apply to urllib , it’s better to keep the decorator as before. As such, you can use it in many places.

There are a few things you can do to improve your decorator. If the program has tried it enough times and it still fails, you will see it raise the last error. Decorator will also wait 3 seconds after the last failure and this may be something you do not want. Feel free to change it to your liking!

Adding a Python sleep() Call With Threads

There are times when you want to add a sleep() call to a thread . Maybe you’re running a migration script with millions of records in production. You don’t want to cause downtime but don’t want to wait longer than necessary to complete the migration, so you decide to use threads.

Note: Thread is a way of implementing concurrency in Python. You can run several threads at the same time to increase program performance. If you are new to the thread, you can check out the article An Intro to Threading in Python .

To prevent customers from paying attention to any delays, each thread needs to run for a short time, then go to bed. There are two ways to do this:

  1. Use time.sleep() as above
  2. Use Event.wait() from the threading module

Please start from time.sleep() .

Using time.sleep()

Logging Cookbook gave a great example using time.sleep() . The logging module is thread-safe, so it’s a little more useful than print () for this exercise. The following code is based on this example:

Here, you use the threading module to create two threads. You also create a logging object that is responsible for logging threadName into stdout. Next, you start both threads and initialize a loop from the main thread continuously. You use the KeyboardInterrupt to start the operation ^Ctrl + C from the user.

Try running the above code in the terminal, you will see the output like the following:

When each thread runs and then sleep, logging will be printed to the console. Through this example, you can use these concepts in your own code.

Using Event.wait()

The threading module provides Event() that you can use as time.sleep() . However, Event() has the advantage that it responds better. The reason for this is that when the event is set, the program exits the loop immediately. With time.sleep() , your code will need to wait for the sleep() call to finish before the thread can exit.

The reason you want to use wait() here is because wait() is non-blocking while time.sleep() is blocking . What this means is that when you use time.sleep() , you will block the main thread and it will not continue running while waiting for the sleep() call to finish. wait() solves this problem. You can read more about all threading-related things in the documentation of Python.

This is how you add a sleep() call to Event.wait() :

In this example, you create threading.Event() and pass it to worker() . (Recall in the previous example, you passed a dict.) Next, you can set up loops to check if the event has been set. If not, your code will print a message and wait a bit before checking again. To set up an event, press ^Ctrl + C Once the event has been set, worker() will return, the loop will be broken and the program will end.

Source: https://realpython.com/python-sleep/

Share the news now

Source : Viblo