Python script that is executed every 5 minutes
In this article, we will discuss how to execute a Python script after every 5 minutes. Let’s discuss some methods for doing this.
Method 1: Using Time Module
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
We can create a Python script that will be executed at every particular time. We will pass the given interval in the time.sleep() function and make while loop is true. The function will sleep for the given time interval. After that, it will start executing.
Method 2: Using Schedule Module
With the help of the Schedule module, we can make a python script that will be executed in every given particular time interval.with this function schedule.every(5).minutes.do(func) function will call every 5 minutes. And with the help schedule.run_pending() we will check whether the scheduler has a pending function to run or not.
Method 3: Using crontab
The Cron job utility is a time-based job scheduler in Unix-like operating systems. Cron allows Linux and Unix users to run commands or scripts at a given time and date. Once can schedule scripts to be executed periodically.
Below is the sample program for demonstration:
The crontab scheduling expression has the following parts:
To schedule our script to be executed, we need to enter the crontab scheduling expression into the crontab file. To do that, simply enter the following in the terminal:
You might be prompted to select an editor, choose nano and append the following line to the end of the opened crontab file:
*/5 * * * * /home/$(USER)/my_script.py
After running the scripts our python scripts executed in every 5 minutes.