调度django自定义命令

时间:2010-12-23 14:54:49

标签: django cron

我很难让我的自定义命令按计划运行。我尝试了一个cronjob和django-chronograph,但我似乎无法从命令行中(成功地)运行它。

我只是使用Ubunutu上安装的django在本地开发应用程序。

我有一个自定义命令,用于清除超过30天的日志条目。为了反复测试它,我对它进行了修改,以便它只删除一个有点任意的条目:

from datetime import datetime, timedelta
from hitcount.models import Hit
from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    args = '<days>'
    help = 'Clear out all Hits that occured over "days" days ago'

    def handle(self, *args, **options):
        list = Hit.objects.filter(created__lt = datetime.now()-timedelta(days=2) )
        list[0].delete()

        self.stdout.write('Hit deleted - %s' % list[0])

此命令(del_hit.py)位于以下结构中:

/project_dir
   /app
      /management
         __init__.py
         /commands
            __init__.py
            del_hit.py

正如我所说,我可以从project_dir

成功运行此命令
python manage.py del_hit

我尝试安装django-chronograph。这似乎非常有用。它识别了我的命令并允许我从下拉列表中选择它。我按照指示应用了cron:

          • /home/vadmin/development/python/my_proj/manage.py cron

但是,当它尝试执行命令时,它在日志中给出了以下错误:

The job failed to run. The exception was :

Unknown command: u'del_hit'

Traceback (most recent call last):

File "/home/vadmin/development/python/my_proj/chronograph/models.py", line 213, in handle_run
call_command(self.command, *args, **options)

File "/usr/lib/python2.6/dist-packages/django/core/management/__init__.py", line 155, in call_command
raise CommandError("Unknown command: %r" % name)

CommandError: Unknown command: u'del_hit'

我尝试从标准视图中自行运行命令:

from django.core.management import call_command
def test_del(request):
    list = Hit.objects.filter(created__lt = datetime.now()-timedelta(days=2) )

    args = []
    options = {}
    call_command('del_hit', *args, **options)

return render_to_response('test.html', {'del_hit_item':list[0]})

已成功执行。

最后,我尝试设置一个cronjob来执行每小时

30 * * * * python /home/vadmin/development/python/my_proj/manage.py del_hit

这不起作用。

我可以使用django-chronograph(最好)或简单的cronjob

让我的自定义命令按计划运行一些帮助

2 个答案:

答案 0 :(得分:4)

看起来您需要位于项目目录中才能正常工作。

尝试更新您调用的命令,先执行'cd',

(cd /home/vadmin/development/python/my_proj && ./manage.py del_hit)

答案 1 :(得分:2)

要编写适合crontab的django脚本,请将这些行放在顶部:

#!/usr/bin/python

from django.core.management import setup_environ
import settings
setup_environ(settings)

如果您的文件不在settings.py的同一文件夹中,请将您的应用文件夹附加到pythons路径。