我使用 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
但是我看不到正在生成的任何日志文件。
有什么方法可以调试这个,操作系统日志之类的吗?
结合这里给出的技巧,这对我来说是这样的:
import os
CRONJOBS = [
('* * * * *', 'myapp.cron.test_cron_run', '>> ' + os.path.join(BASE_DIR,'log/debug7.log' + ' 2>&1 '))
]
补充说明
python3 manage.py crontab add
两次2>&1
,来自 python 的错误消息在写入 STDERR 时不会被记录crontab -l
mail
阅读。也许只需尝试在 cron 作业末尾添加
2>&1
,它会将错误输出重定向到标准输出。
我也有同样的问题。我只能通过包含日志文件的直接路径并提前创建它来使其工作
pip install django-crontab
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
的文件。
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