ubuntu python cron作业没有错误地停止

时间:2016-07-20 14:23:41

标签: python django cron

我有一个运行我网站的亚马逊实例。我最近尝试设置一个cron作业,它只是停止而不会抛出任何错误或任务的任何一半。

crontab -l显示

30 13 * * 1,2,3,4,5,6 /home/ubuntu/.virtualenvs/testprep/bin/python /home/ubuntu/web/testprep/manage.py daily > /tmp/prepcron.log

这是我的python / django脚本:

class Command(BaseCommand):
    def handle(self, *args, **options):
        print("starting")
        date = datetime.now().date()
        print("date is", date)
        try:
            users = User.objects.filter(test="ACT", state__in=[User.WAITING, User.READY, User.SOLUTION])
        except Exception as e:
            print(str(e)) 
        print("number of users", users.count())
        ...

在13:30,我在我的日志文件中得到了这个:

starting
date is 2016-07-19

那就是它!不会抛出或捕获错误。永远不会打印Number of users。该计划刚刚放弃了一半。如果我手动运行该命令(文字复制和粘贴),那么脚本将按预期执行,这只有在我尝试安排它时才会发生。

有没有人见过这样的东西?

1 个答案:

答案 0 :(得分:0)

好的,问题实际上在我的django settings.py文件中。数据库只是一个具有相对路径的sqlite数据库。显然,当从cron作业运行代码时,它需要一个绝对路径。因此,将代码更改为此修复了问题:

import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'database'),
    }
}