Skip to content

[Python] Use “eventlet” Library to Terminate the Program When It Executing the Certain Time

Last Updated on 2022-05-27 by Clay

Recently, when I programming, I had such a strange requirement: the program will solve a problem in about a minute, but if it takes more than a minute, it needs to give up and move on the next task.

It has also been queried on the Internet that some developers may need to calculate the number of seconds that the program executes. If it exceeds a certain time, it judged that the system is stuck and the program needs to be terminated.

These requirements can be solved by eventlet library in Python.


Introduction of eventlet

I’m not going to record the principle of the eventlet library in too much detail here. After all, the project I’m working on is about to end, and I’m in a hurry to make this record; in addition, most of the notes on the Internet have been recorded in great detail.

In short, eventlet implements the so-called green thread, which is a fake concurrency, but actually works within a single thread.

The advantage of this is that it consumes less energy, and it can also perform additional timing without blocking our work – yes, that’s what I want to record today: terminate the program after the program has been executed for more than a certain time.

The following is a sample.


How to use eventlet library

Inevitably, we need to use pip tool to install package:

pip3 install eventlet


After installation, let’s take a look at a short code:

import time
import eventlet


def main():
    # Init
    eventlet.monkey_patch()
    i = 0

    while True:
        isContinue = False

        with eventlet.Timeout(5, False):
            i += 1
            print("{}s...".format(i))
            time.sleep(i)

            # If program execute here, the while-loop will continue
            isContinue = True
    
        # break out the while-loop
        if isContinue == False:
            break

    # Display the stop point
    print("The program is stop at i={}!".format(i))


if __name__ == "__main__":
    main()


Output:

1s...
2s...
3s...
4s...
5s...
The program is stop at i=5!

As you can see, I create a isContinue variable, when the program is finished in 5 seconds, the isContinue variable assign to True, so the while-loop will continue; but if not, we will jump out from loop, terminate the program.

It can be easily be added to my existing program, so I am documenting it here.


References


Read More

Tags:

Leave a Reply