如何debud django crontab?

问题描述 投票:0回答:4

我使用 django crontab 设置了一个 cron 作业。根据文档中的定义,我在 cron.py 中定义了一个测试作业,并在 settings.py 中将其定义为以 1 分钟间隔运行。

#cron.py
def test_cron_run():
    print("\n\nHello World....!! ",timezone.now())

#settings.py
INSTALLED_APPS = [
    'material.theme.cyan',
    'material',
    'material.admin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    'django_crontab',
]

CRONJOBS = [
    ('*/1 * * * *', 'myapp.cron.test_cron_run','>>'+os.path.join(BASE_DIR,'log/debug7.log')),
]

我通过运行

python3 manage.py crontab add
添加了 cron 作业。 还添加了作业,因为我可以看到我是否运行,
python3 manage.py crontab show
但是我看不到正在生成的任何日志文件。 有什么方法可以调试这个,操作系统日志之类的吗?

python django cron django-cron
4个回答
5
投票

结合这里给出的技巧,这对我来说是这样的:

import os

CRONJOBS = [
    ('* * * * *', 'myapp.cron.test_cron_run', '>> ' + os.path.join(BASE_DIR,'log/debug7.log' + ' 2>&1 '))
]

补充说明

  • 该目录需要存在并且需要有写权限
  • 每次更改 CRONJOBS 后,运行
    python3 manage.py crontab add
    两次
  • 如果没有
    2>&1
    ,来自 python 的错误消息在写入 STDERR 时不会被记录
  • 使用
    crontab -l
  • 检查实际写入 crontab 的内容
  • 如果它不起作用,您可能会收到来自 cron 的邮件。根据您的系统,请使用
    mail
    阅读。

1
投票

也许只需尝试在 cron 作业末尾添加

2>&1
,它会将错误输出重定向到标准输出。


1
投票

我也有同样的问题。我只能通过包含日志文件的直接路径并提前创建它来使其工作


0
投票
  1. pip install django-crontab
  2. 打开
    settings.py
    文件

现在将这些行添加到您的

settings.py
文件中

import os
from django.utils.log import DEFAULT_LOGGING
import logging.config

LOG_DIR = os.path.join(BASE_DIR, 'log')
if not os.path.exists(LOG_DIR):
    os.makedirs(LOG_DIR)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'cron_file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOG_DIR, 'cron_job.log'),
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'student': {
            'handlers': ['cron_file'],
            'level': 'DEBUG',
            'propagate': False,
        },
    },
}

注意:确保您有

log
目录,并且在日志目录中您有在记录器设置中定义的名为
cron_job.log
的文件。

  1. 现在在您的任何
    cron.py
    中创建名为
    app
    的文件。 例如 我有一个名为
    student
    的应用程序,在我的应用程序中我有文件名
    cron.py
    文件。

这是我的

cron.py
文件代码

import logging
from django.utils import timezone
from datetime import timedelta
from student.models import ForgotPasswordAttempt

logger = logging.getLogger('student')


def delete_old_attempts():
    logger.info('Deleting old attempts')
    now = timezone.now()
    time_threshold = now - timedelta(hours=8)

    attempts_to_delete = ForgotPasswordAttempt.objects.filter(
    forgot_password_attempt__gt=5
    ) | ForgotPasswordAttempt.objects.filter(
    updated_at__lt=time_threshold
    )

    count, _ = attempts_to_delete.delete()
    logger.info(f'Deleted {count} ForgotPasswordAttempt objects')

现在在您的

terminal

中运行这些命令
# to Add
python manage.py crontab add
# to Show
python manage.py crontab show
# to Remove
python manage.py crontab remove

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.