Many companies use the Python programming language for data science applications, machine learning models, and other types of analytical tasks. Since Python is often only used for specific projects, many businesses have to integrate it into their workflow programmatically. This means they need a way to automate the process so it runs independently when needed and on a schedule. Fortunately, there are ways to integrate Python with cron jobs to automate execution as frequently as necessary.
In this article, you will learn how to schedule Python using cron and some useful examples of when and how you might use these practices in your organization.
Running Python Script with Crontab
I have created a sample Python application, that required a script to run every 15 minutes. You can use
crontab -e to open the crontab editor and add the job as below:
A Python script can be configured using one of the below options depending on the environment:
- Default Python Version: If the application runs with system default Python version, use below crontab settings:
*/15 * * * * python /home/tecadmin/app/cron.py
- Non-default Python Version: You can use other Python versions by providing the complete binary path. Some applications required a Python version that is not set as default on the system
*/15 * * * * /usr/bin/python3.10 /home/tecadmin/app/cron.py
- Python with Virtual Environment: The applications running with the Python virtual environment can be scheduled as below. Here
/home/tecadmin/app/venvis the directory containing virtual environment files.
*/15 * * * * /home/tecadmin/app/venv/bin/python /home/tecadmin/app/cron.py
In this quick how-to tutorial, you have learned to schedule Python scripts with crontab in Linux and macOS systems.