Open In App

Python script that is executed every 5 minutes

Last Updated : 13 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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

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.

Code:

Python3




import time
  
  
while(True):
    print('hello geek!')
    time.sleep(300)


Output:

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.

Code:

Python3




import schedule
import time
  
def func():
    print("Geeksforgeeks")
  
schedule.every(1).minutes.do(func)
  
while True:
    schedule.run_pending()
    time.sleep(1)


Output:

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:

Python3




#! /usr/bin/python3
  
def main():
    print("Hello Geeks")
  
if __name__ == '__main__':
    main()


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:

crontab -e

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads