how to use django-background-tasks

前端 未结 4 1263
离开以前
离开以前 2020-12-30 14:39

I am making a django application. To calculate the rank of the feeds based on lines and comment, I am trying to use django-background-tasks. the function I am using in nodes

4条回答
  •  独厮守ぢ
    2020-12-30 15:32

    You seem to be using it the wrong way.

    Let's say you have to execute some particular task say, send a mail 5 minutes after a user signs up. So what do you do is:

    Create a task using django-background-task.

    @background(schedule=60*5)
    def send_html_mail_post(id, template):
        u = User.objects.get(id=id)
        user_email = u.email
        subject = "anything"
        html_content = template.format(arguments)
        from_email, to = from_email, user_email
        text_content = ''
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send()
    

    The decorator at the top defines after how much time of the function getting called upon is the actual event gonna happen.

    Call it when you need it.

    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            up = UserProfile.objects.create(user=instance)
            up.save()
            tasks.send_welcome_email(up.user.id, template=template)
    

    This creates the task and saves it in database and also storing in db the time when it will be executed.

    The kind of thing you want to do, doing something at regular intervals, that can more easily be done by creating cron job.

    What you do is, you create a function as you have shown in the question. And then define a cron job to call it every 5 minutes or whatever interval you want.

提交回复
热议问题