How To Run Django Management Commands From Cron With Virtualenv?

Published July 13, 2024

Problem: Running Django Management Commands via Cron with Virtualenv

Running Django management commands through cron jobs while using a virtual environment can be difficult. The main issue is how to activate the virtual environment and access the Django project's settings within the cron job context.

Solution: Running Django Management Commands with Cron and Virtualenv

Method 1: Direct Python Execution

To run Django management commands with cron and virtualenv:

  • Use the virtual environment's Python executable
  • Specify the full path to manage.py

Example of a cron job:

0 3 * * * cd /home/user/project && /home/user/project/env/bin/python /home/user/project/manage.py command arg

This method uses the Python interpreter from your virtual environment to run the Django management command.

Tip: Environment Variables in Cron

When using cron, remember that it runs with a limited environment. If your Django project relies on specific environment variables, you may need to set them in the cron job or source a file that sets them:

0 3 * * * source /path/to/env_vars.sh && cd /home/user/project && /home/user/project/env/bin/python /home/user/project/manage.py command arg

Method 2: Using a Wrapper Script

Another way to run Django management commands with cron and virtualenv is by creating a wrapper script:

  • Create a shell script to activate the virtual environment
  • Execute Django commands within the script

Example of a wrapper script:

#!/bin/sh
source /home/user/project/env/bin/activate
cd /home/user/project/
./manage.py command arg

Save this script with a .sh extension, make it executable with chmod +x script_name.sh, then set up your cron job to run this script:

0 3 * * * /path/to/your/script_name.sh

This method allows you to perform setup steps before running the Django command.