How to automatically run a Python script on your server using Cron

Every now and again you may need a script to run daily or hourly on your server. I use this at work and home to automate some functions in life.

Every now and again you may need a script to run daily or hourly on your server. I use this at work and home to automate some functions in life.

First get a Python script written up and stable, then automate it with Cron.

Check out Crontab.guru for examples on the best timing. In the example below I have Cron run the command every 30 minutes.

Open and edit your crontab:

crontab -e

Copy in the following noting to change to your needs

# Setup our PATH
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# On /bin/sh 'source' wonn't work, so force Bash
SHELL=/bin/bash
# Setup our directory
DIR_SMTH="cd /home/d4t4/python_app_dir"
# Activate your virtualenv
VENV=". venv/bin/activate"
# Source your environment variables
SRC="source /home/d4t4/python_app_dir/.env"
# Setup your command [run the script]
CMD="python py_app.py"

# Setup to run every 30 minutes
# m h  dom mon dow   command
*/30 * * * * $DIR_SMTH && $VENV && $SRC && $CMD >> /home/d4t4/python_app_dir/crontest.log 2>&1

Wait patiently as your server does the work.


My blog posts tagged with "Python Patterns" are designed to be a quick look reference for some Python code snippets I use a lot.  They are written to be a quick starting point for future projects so I do not need to type as much.