How to Schedule Python Scripts As Cron Jobs With Crontab
In this article, we will discuss how to schedule Python scripts with 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. One can schedule scripts to be executed periodically. The crontab is a list of commands that you want to run on a regular schedule, and also the name of the command used to manage that list. cron is the system process that will automatically perform tasks for you according to a set schedule.
Below is a simple Python script that sends a notification message to remind the user to drink water. We will be scheduling this script to send a notification every 2 hours. (the script is tested for Linux-based systems only, but the scheduling process will be similar with any script)
Note: #!/usr/bin/python3 (specifying the path of script interpreter) is necessary if wish to make the script executable. Assuming we have saved this script as my_script.py under our home directory, we can make it executable by entering the following command in our terminal:
$ sudo chmod +x my_script.py
We can test our script if it is working properly:
This will send a notification as the message “drink water”.
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:
* */2 * * * /home/$(USER)/my_script.py
where $(USER) can be replaced with your username. Save changes and exit. This will schedule our Python script to run every 2 hours.
Verify the file was successfully saved:
It will list all the scheduled jobs.
There are a few things to keep in mind before scheduling cron jobs:
- All cron jobs are scheduled in the local time zone in which the system where the jobs are being scheduled operates. This could be troublesome if jobs are being scheduled on servers with multinational personnel using it. Especially if the users also belong to countries that follow Daylight Savings Time practice.
- All cron jobs run in their own isolated, anonymous shell sessions and their output to STDOUT (if any) must be directed to a file if we wish to see them.
- All cron jobs run in the context of the user for which they were scheduled. It is therefore always good practice to provide an absolute path to scripts and output files to avoid any confusion and cluttering.
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