In Python programming, there might be certain scenarios where you would want your program to stop after a set duration.
This could be useful when you are running a task that could potentially take up too much time and you want to automatically terminate it if it surpasses a stipulated time limit.
Today, we are going to walk you through how to automatically end a Python program after a certain period of time.
Step 1: Import Required Libraries
The first step is to import the required Python libraries that enable us to implement time constraints. In this case, we are going to use the threading and time library.
1 2 |
import threading import time |
Step 3: Define a Function to Execute
For our program, we are going to define a simple function. This function would typically be a task you want your Python program to perform. Here, our function will just print Hello, World!
continuously every second.
1 2 3 4 |
def function_to_exec(): while not stop_thread: print('Hello, World!') time.sleep(1) |
Step 3: Define Your Stop Function
Next, we define a function that will stop our previously defined function after a certain period.
1 2 3 4 |
def stop_function_after(delay): global stop_thread # Access the global flag time.sleep(delay) stop_thread = True |
Step 4: Execute the Function with a Defined Stop Time
Now, we can execute our function and stop it after a defined time. We’ll keep the duration as 5 seconds here.
1 2 3 |
thread = threading.Thread(target=function_to_exec) thread.start() stop_function_after(5) |
Complete Code
The full code of our Python program to stop after a set period is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import threading import time # Create a flag to control the thread stop_thread = False def function_to_exec(): while not stop_thread: print('Hello, World!') time.sleep(1) def stop_function_after(delay): global stop_thread # Access the global flag time.sleep(delay) stop_thread = True thread = threading.Thread(target=function_to_exec) thread.start() stop_function_after(5) |
Conclusion
That’s it! With these steps, you can easily setup an automatic termination for a Python program after a certain period of time.
This is especially helpful in instances where you are running a task that might potentially run indefinitely or take up too much time. Use this tutorial as your guide to automate your tasks intelligently.