如何在服务器运行时启动命令管理?

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

我是Django的新手,我正在为uni项目创建一个Web应用程序。我必须定期发送电子邮件,并且这样做我正在使用管理命令,但我不知道如何在启动服务器时自动运行它。我正在使用Windows 8.1中的Pycharm

from django.core.mail import send_mail
from django.core.management.base import BaseCommand
from ProgettoDinamici.settings import EMAIL_HOST_USER
from products.models import Notification
from users.models import User

class Command(BaseCommand):
    help = 'Sends emails periodically'

    def handle(self, *args, **options):
        users = User.objects.all()
        for u in users:
            try:
                notify = Notification.objects.filter(receiver=u, read=False)
                count = notify.count()
            except:
                print("No notification found")
            try:
                if notify:
                    send_mail(
                        'E-Commerce',
                        'You have ' + str(count) + ' notifications.',
                        EMAIL_HOST_USER,
                        [u.email],
                        fail_silently=False,
                    )
            except:
                print("error")

现在我尝试使用schedule和cron每n分钟重复一次send_email,但没有任何工作,在线搜索我发现cron(和基于cron)不受Windows支持。但这是另一个问题......

python django windows scheduled-tasks
1个回答
1
投票

您可以使用芹菜进行定期任务。只需将函数handle转换为芹菜任务,您就可以在该任务上安排cron作业。

你可以参考:https://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html

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