我很难让我的自定义命令按计划运行 . 我已经尝试了一个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
这没用 .
I could use some assistance in getting my custom command to run on a schedule using either django-chronograph (preferably) or a simple cronjob
2 回答
看起来您需要位于项目目录中才能使其正常工作 .
尝试更新您调用的命令,先执行'cd',
(cd /home/vadmin/development/python/my_proj && ./manage.py del_hit)
要编写适合crontab的django脚本,请将这些行放在顶部:
如果您的文件不在settings.py的同一文件夹中,请将您的app文件夹附加到pythons路径 .