在 Django 中使用 crontab [英] Using crontab with django

查看:21
本文介绍了在 Django 中使用 crontab的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个每天从 crontab 发送时事通讯的函数.我在互联网上找到了两种方法:

I need to create a function for sending newsletters everyday from crontab. I've found two ways of doing this on the internet :

第一个-放在django项目文件夹中的文件:

First - file placed in the django project folder:

#! /usr/bin/env python
import sys
import os

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

from django.core.mail import send_mail
from project.newsletter.models import Newsletter, Address

def main(argv=None):
    if argv is None:
        argv = sys.argv

    newsletters = Newsletter.objects.filter(sent=False)
    message = 'Your newsletter.'

    adr = Address.objects.all()
    for a in adr:
        for n in newsletters:
            send_mail('System report',message, a ,['user@example.com'])

if __name__ == '__main__':
    main()

我不确定它是否会起作用,也不知道如何运行它.假设它被称为 run.py,那么我应该在 cron 中使用 0 0 * * * python/path/to/project/run.py 调用它 ?

I'm not sure if it will work and I'm not sure how to run it. Let's say it's called run.py, so should I call it in cron with 0 0 * * * python /path/to/project/run.py ?

第二个解决方案 - 在任何地方创建我的发送函数(就像一个普通的 django 函数),然后创建一个 run.py 脚本:

Second solution - create my send function anywhere (just like a normal django function), and then create a run.py script :

import sys
import os

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

module_name = sys.argv[1]
function_name = ' '.join(sys.argv[2:])

exec('import %s' % module_name)
exec('%s.%s' % (module_name, function_name))

然后在 cron 调用中:0 0 * * * python/path/to/project/run.py newsletter.views daily_job()

And then in cron call : 0 0 * * * python /path/to/project/run.py newsletter.views daily_job()

哪种方法有效,或者哪种更好?

Which method will work, or which is better ?

推荐答案

我建议将您的功能创建为 django-management-command 并通过 crontab 运行它

i would suggest creating your functionality as django-management-command and run it via crontab

如果你的命令是 send_newsletter 那么简单

if your command is send_newsletter then simply

0 0 * * * python /path/to/project/manage.py send_newsletter

并且在这种情况下您不需要设置设置模块/

and you don't need to take care of setting the settings module in this case/

这篇关于在 Django 中使用 crontab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆