Scheduling Python Scripts on Linux
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.
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
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:
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.
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
To remove the job from the crontab, run this command.
crontab -r : This will delete the current cron jobs.