Python Engineer

Python and Machine Learning Tutorials

How To Schedule Python Scripts As Cron Jobs With Crontab (Mac/Linux)

07 Jan 2021

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.


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

The syntax

For the syntax I recommend to visit

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:

Pitfalls when running Python scripts

  1. Use the full path to your file, e.g.:
* * * * * python ~/code/python-task-automation/
  1. 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)
  1. 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/ or * * * * * ~/code/python-task-automation/venv/bin/python ~/code/python-task-automation/