How To Schedule Python Scripts As Cron Jobs With Crontab (Mac/Linux)
In this tutorial, we learn about cron jobs and how to schedule commands and Python scripts in the terminal via crontab
(for Linux and Mac). This allows us to run commands on a repetitive schedule. We specifically look into running Python scripts as cron jobs. There are a couple of pitfalls where we have to be careful. We also learn how to schedule jobs with a virtual environment.
The code is also available on GitHub.
Crontab
We can schedule jobs with the crontab
command. A crontab file is a simple text file containing a list of commands meant to be run at specified times. It is edited using the crontab command. The commands in the crontab file are checked by the cron daemon, which executes them in the system background.
List all scheduled cron jobs with:
$ crontab -l
Edit the file by using the command:
$ crontab -e
Then use the following syntax to schedule a job
* * * * * command
For example to run a python script use:
* * * * * python my_script.py
The syntax
For the syntax I recommend to visit crontab.guru.
The 5 items are used to specify minute, hour, day in the month, month, and day in the week
(in this order). The following characters can be used for more complex timing:
*
any value,
value list separator-
range of values/
step values
Pitfalls when running Python scripts
- Use the full path to your file, e.g.:
* * * * * python ~/code/python-task-automation/test.py
- When logging into files, specify the full path for the filename in the Python file. Otherwise the file just ends up in your home directory.
import logging
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(dir_path, 'test_log.log')
# Logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler(filename)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(file_handler)
- When a virtual environment is used, specify the full path to the python executable, e.g.:
* * * * * ~/opt/miniconda3/envs/py38/bin/python ~/code/python-task-automation/fetch_github.py
or
* * * * * ~/code/python-task-automation/venv/bin/python ~/code/python-task-automation/fetch_github.py

FREE NumPy Handbook
Learn NumPy with this eBook! It covers code examples for all essential functions. Get it for free together with monthly Python tips and news.