简体   繁体   中英

How can I start a command management when server is running?

I'm new in Django and I am creating a web application for uni project. I have to send emails periodically, and to do so I'm using a management command, but I don't know how to make it automatically run when I start the server. I'm working on Pycharm in Windows 8.1

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")

For now I tried to use schedule and cron to repeat the send_email every n minutes, but nothing worked and searching online I found out that cron (and cron based) ins't supported by Windows. But this is another problem...

You can use celery for periodic tasks. Just convert the function handle into a celery task and you can schedule cron jobs on that tasks.

You can refer: https://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM