views:

805

answers:

4

I want my custom made Django command to be executed every minute. However it seems like python /path/to/project/myapp/manage.py mycommand doesn't seem to work while at the directory python manage.py mycommand works perfectly.

How can I achieve this ? I use /etc/crontab with:

****** root python /path/to/project/myapp/manage.py mycommand
+4  A: 

I think the problem is that cron is going to run your scripts in a "bare" environment, so your DJANGO_SETTINGS_MODULE is likely undefined. You may want to wrap this up in a shell script that first defines DJANGO_SETTINGS_MODULE

Something like this:

#!/bin/bash

export DJANGO_SETTINGS_MODULE=myproject.settings
/path/to/project/myapp/manage.py mycommand

Make it executable (chmod +x) and then set up cron to run the script instead.

Edit

I also wanted to say that you can "modularize" this concept a little bit and make it such that your script accepts the manage commands as arguments.

#!/bin/bash

export DJANGO_SETTINGS_MODULE=myproject.settings
/path/to/project/myapp/manage.py ${*}

Now, your cron job can simply pass "mycommand" or any other manage.py command you want to run from a cron job.

Joe Holloway
This says unknown command when I do it. I had to change it to:cd /path/to/project./manage.py ${*}
mhost
+4  A: 

If you want your Django life a lot more simple, use django-command-extensions within your project:

http://code.google.com/p/django-command-extensions/

You'll find a command named "runscript" so you simply add the command to your crontab line:

****** root python /path/to/project/myapp/manage.py runscript mycommand

And such a script will execute with the Django context environment.

nabucosound
A: 

The runscript extension wasn't well documented. Unlike the django command this one can go anywhere in your project and requires a scripts folder. The .py file requires a run() function.

sherwoodiv
A: 
cd /path/to/project/myapp && python manage.py mycommand

By chaining your commands like this, python will not be executed unless cd correctly changes the directory.

davidfischer