我是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。但这是另一个问题...
2条答案
按热度按时间cmssoen21#
你可以使用celery来处理周期性的任务。只要将函数
handle
转换成celery任务,你就可以在这个任务上安排cron作业。您可以参考:https://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html
lnxxn5zx2#
我知道这是一个老问题,但希望有人会发现这个有用。
看起来你只是想在windows机器上以一定的间隔运行一个脚本。
windows相当于一个cron作业是一个计划任务,有一篇关于它的文章here。
然而,你真的应该考虑你部署的代码将生存的环境。如果是 *nix环境,windows dev环境会让事情变得困难。我建议使用linux dev环境,也许在VM中,或者通过在docker容器中运行代码。