0
votes

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...

1
This question might help - Alasdair
use a cronjob with the python command with full path. - Eddwin Paz
Thank you for the answer. I searched the internet and I found out that cron/cronjob/schedule/etc doesn't work on windows, that's why I'm having all these problems - malandrino95
Alasdair, thank you too, but this doesn't solve my problem, because in this way I have to start the scheduled task giving a cmd or by windows scheduler, but this is not what I want. What I want is to run the scheduled task when the server of my web app is running (after I run python manage.py runserver to be clear) - malandrino95

1 Answers

1
votes

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