0

I am a bit lost here. I want to send email using django on a post request. But I don't want the user to wait for a reply so I am sending it in a background thread. Also the emails are to be send every 30 seconds in a sequential order provided by the user.

But there is a option for the user to cancel sending the emails i.e a different post request to handle the cancel input.

How do I listen for cancel operation in the thread sending the email? How do I implement the 30 second delay? I thought of using sleep but if I do that then will it skip the cancel signal?

Cœur
  • 37,241
  • 25
  • 195
  • 267
sam23
  • 589
  • 2
  • 7
  • 23
  • You should be careful with extra threads in WSGI applications. They often cause troubles in the WSGI servers. You could store the mails to send in the DB and run an extra process as a management command to send them. – Klaus D. Jun 08 '17 at 10:56
  • I would agree with @KlausD., you can make the entry in DB and an associated field for the status of that email. Another script would be listening for these from the DB and accessing at some defined interval. And if you receive cancel request in between. Change the status of those emails to cancelled. – harshil9968 Jun 08 '17 at 11:01
  • 2
    Seems like a perfect use-case for celery... – bruno desthuilliers Jun 08 '17 at 11:10
  • 1
    In addition to classical approach with Celery, you could take a look at channels: https://channels.readthedocs.io/ – Ivan Jun 08 '17 at 11:27
  • Possible duplicate of [Threading in Django is not working in production](https://stackoverflow.com/questions/44126586/threading-in-django-is-not-working-in-production) – e4c5 Jun 08 '17 at 11:49

1 Answers1

1

As mentioned above, it would probably be the case of using a Celery task for sending the e-mails asynchronously. Then, for cancelling the e-mails sending, your view handling the POST (for cancelling) request could revoke the tasks responsible for sending that sequence of e-mails. This question/answer shows how to do it.

Lucas Infante
  • 798
  • 6
  • 21