Ricky
Ricky

Reputation: 883

How can I run a Python File in a Django Environment using Crontab?

I'm trying to make a Crontab job that will run a Python script once everyday at 4AM.

Here is my crontab line

0 4 * * * cron_scripts/scripttorun.py

The file is being linked correctly, and it's attempting to execute it. However, when it tries to execute the file it gives me some errors based on my imports. Here is the part of my python file that causes the crash, it crashes on the first line because it's not importing the file correctly for some reason...

from history.models import Model1
from users.models import User

I am trying to run the Python File with some other code from my web server, that uses Django. Do I have to do something extra in order to be able to import my models?

I get the same result when I run python scripttorun.py.

Upvotes: 1

Views: 1440

Answers (4)

The Django Ninja
The Django Ninja

Reputation: 393

You should take a loot at the runscript command from Django-extensions

It let you create easy Django management command, with all the django environnement in it.

Then you can set a cron to execute the task periodically.


Django Extensions provide other useful tools for your Django project, take a look at it.

Upvotes: 0

Martol1ni
Martol1ni

Reputation: 4702

My personal suggestion here is to create a new command in app/management/commands/yourcommand.py

from django.core.management.base import BaseCommand, CommandError


class Command(BaseCommand):
    help = "Might wanna add a help text"
    args = '<arg>' # need args?

    def handle(self, *args, **options):
        # Do whatever you want to do 

Then run that from your crontab.

/path/to/python /path/to/manage.py name_of_command

Upvotes: 1

WeizhongTu
WeizhongTu

Reputation: 6424

You can also do it like this:

do_something.py

#! /usr/bin/python
#coding:utf-8
from __future__ import unicode_literals

import os
os.environ["DJANGO_SETTINGS_MODULE"] = "prj.settings"

from app.models import YourModel

# do something

put the file the same place with manage.py

How to use, you can write a .sh script

cd pjc-directory
python do_something.py

then run this script with crontab

Upvotes: 0

aldo_vw
aldo_vw

Reputation: 638

In Django you can write custom django-admin commands. Just check this: https://docs.djangoproject.com/en/dev/howto/custom-management-commands/

Then you include in the crontab file: 0 4 * * * python /path/to/myapp/manage.py scriptorun.py

Upvotes: 2

Related Questions