To run a Python script on a schedule, add a line to your crontab with the full path to the Python interpreter and to the script. This runs report.py every 5 minutes:
*/5 * * * * /usr/bin/python3 /opt/app/report.py >> /var/log/app/report.log 2>&1
The sections below cover what makes that line work every time: virtual environments, paths, environment variables, output buffering, overlapping runs, Django and how to find out when it stops.
Add the cron job
- Find the interpreter with
which python3. Cron runs with a shortPATH, so write the full path, like/usr/bin/python3. - Open the crontab with
crontab -e, orsudo crontab -u www-data -eto run as another user. - Add the line and save. Cron reads the change on its own.
- Check it with
crontab -l.
Other schedules: every hour, all common schedules, or build one with the cron expression generator.
Virtual environments
You don't need to activate a virtual environment in cron. Call the Python inside it, and it uses the packages installed there:
*/5 * * * * /opt/app/.venv/bin/python /opt/app/report.py
The same works for Poetry and pipenv: find the interpreter with poetry env info --path or pipenv --venv and add /bin/python.
Paths and the working directory
Cron starts the script in your home directory, so a relative open('config.json') fails there. Build paths from the script's own folder:
from pathlib import Path
BASE = Path(__file__).resolve().parent
config = (BASE / 'config.json').read_text()
Or change directory in the crontab first:
*/5 * * * * cd /opt/app && .venv/bin/python report.py
Environment variables
Cron doesn't read .bashrc or .profile, so variables you export there are missing. Set them at the top of the crontab:
DATABASE_URL=postgres://app@localhost/app
*/5 * * * * /opt/app/.venv/bin/python /opt/app/report.py
Or keep them in a .env file next to the script and load it with python-dotenv, passing the full path to load_dotenv.
Logs and output buffering
Redirect the output to a file, or it goes to local mail and usually nowhere:
*/5 * * * * /opt/app/.venv/bin/python -u /opt/app/report.py >> /var/log/app/report.log 2>&1
The -u matters. When output goes to a file instead of a terminal, Python buffers it, so lines show up late, and the last ones are lost if the process is killed. -u (or PYTHONUNBUFFERED=1 in the crontab) writes each line right away. Where the cron log itself is: cron logs.
Stop runs from overlapping
If a run can take longer than the interval, flock skips the next run while the previous one still holds the lock:
*/5 * * * * flock -n /tmp/report.lock /opt/app/.venv/bin/python /opt/app/report.py
Django management commands
Run them from the project folder with the project's Python:
0 3 * * * cd /srv/app && .venv/bin/python manage.py clearsessions >> /var/log/app/cron.log 2>&1
If the settings module isn't the default, add DJANGO_SETTINGS_MODULE=app.settings.production at the top of the crontab. Libraries like schedule or APScheduler, and Celery beat, schedule tasks from inside a process that has to keep running; cron starts the script fresh each time, which is simpler when you have one or two jobs.
Exit codes
An uncaught exception exits with code 1, which tells cron (and the heartbeat ping below) that the run failed. If you catch errors, exit with a non-zero code yourself:
import sys
if not ok:
print(f'report failed: {reason}', file=sys.stderr)
sys.exit(1)
Get an alert when the job stops
Add a heartbeat ping that only runs when the script exits with 0:
*/5 * * * * /opt/app/.venv/bin/python /opt/app/report.py && curl -fsS -m 10 -X POST https://api.failover.io/heartbeat/<your-monitor-id>
Or send it from the script itself, at the end of a successful run, with no extra package:
import urllib.request
req = urllib.request.Request('https://api.failover.io/heartbeat/<your-monitor-id>', data=b'', method='POST')
urllib.request.urlopen(req, timeout=10)
When a ping is late, you get an alert. See how to monitor cron jobs.
Frequently asked questions
How do I run a Python script with cron?
Add a line with the schedule, the full path to Python and the full path to the script, for example */5 * * * * /usr/bin/python3 /opt/app/report.py, with crontab -e.
How do I use a virtual environment in a cron job?
Call the venv's Python directly, like /opt/app/.venv/bin/python. There is no need to activate it.
Why does my Python script work in the terminal but not in cron?
Usually a relative path, a missing environment variable or the wrong interpreter. Use absolute paths, set variables in the crontab and call the venv's Python. Log the output to see the error.
Why is my cron log empty or late?
Python buffers output when it isn't writing to a terminal. Run it with python -u or set PYTHONUNBUFFERED=1.