Open In App

Scheduling Python Scripts on Linux

Last Updated : 31 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes we need to do a task every day, and we can do these repetitive tasks every day by ourselves, or we can use the art of programming to automate these repetitive tasks by scheduling the task. And today in this article we are going to learn how to schedule a python script on Linux to do the repetitive tasks.

We are going to a utility called cron to schedule the python script. Cron is driven by crontab which is also referred to as timetable because the word cron is derived from the Greek word Chronos which means time and tab is simply table.

Syntax: * * * * * command

In Crontab there are six fields. The first five are reserved for the date and time of scheduled execution, and the last field is reserved for a command to be executed.

Here is the python script that we are going to schedule:

Python3




#!/usr/bin/env python3
  
# importing libraries
import os
import random
  
# setting up folder name
folder_name = "geeksforgeeks"
  
# entering into the loop
# to create 2 folder every time this script runs
for i in range(2):
  
    # generating random number between 0 and 9
    number = int(random.randrange(0, 10))
  
    print("Creating folder {}".format(number))
  
    # creating directories
    os.mkdir(folder_name+" {}".format(number))


Output:

Scheduling Python Scripts on Linux:

Now following are the steps we need to be followed to schedule python scripts in Linux:

Step 1: Firstly, we have to create a python script that we will be going to schedule.  Above is the python script that we are going to use in this article.

Step 2: Open up the crontab to create a configuration file for scheduling the python script.

Step 3: Run the following command in the terminal to open up the crontab configuration file.

crontab -e

This should open up an editor to edit the configuration file and the output should look like this:

Step 4: Scroll to the end of the file and write down the timing and the command to be executed.

* * * * * /usr/bin/env python3 /home/amninder/Desktop/Geeks/cron/schedule.py >> /home/amninder/Desktop/Geeks/cron/output.txt

Here, “/usr/bin/env python3 /home/amninder/Desktop/Geeks/cron/schedule.py ” is the path to the script that we are going to schedule and “/home/amninder/Desktop/Geeks/cron/output.txt” is the path to the file where we are going to save our output. Asterisks (*) on all first 5 fields indicate that the script is going to execute after every minute, every hour.

To check logs to see if It’s working or not run the following command:

sudo tail -f /var/log/syslog

Output:

To remove the job from the crontab, run this command.

crontab -r : This will delete the current cron jobs.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads