如何使用django-background-tasks [英] how to use django-background-tasks

查看:585
本文介绍了如何使用django-background-tasks的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在申请django。要基于行和注释来计算提要的排名,我正在尝试使用django-background-tasks。我在节点模型中使用的功能是:

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 models is:

    @background(schedule=60)
    def get_score(self):
        p = self.likes+self.comments    # popularity
        t = (now()-self.date).total_seconds()/3600  # age_in_hrs
        # last_activity =
        n = self.admin_score
        score = (p/pow((t+1), 1.2))*n
        self.score = score
        return score

但是我没有看到分数的任何变化。这意味着我正在以正确的方式进行操作,而我却错过了基本概念。有人可以告诉我如何使用django-background-tasks安排任务或将我引向一些现有文档。

But I am not seeing any change in score. That means that I am doing it in a right way and i am missing the basic concept. Can somebody tell me how to use django-background-tasks to schedule task or refer me to some existing documents.

推荐答案

假设您必须执行某些特定任务,例如,在用户注册后5分钟发送一封邮件。因此,您要做的是:

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:

使用django-background-task创建任务。

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.

在需要时调用它。

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.

您要做的是,按照问题中的说明创建一个函数。然后定义一个cron作业,每隔5分钟或您想要的任何时间间隔调用一次。

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.

这篇关于如何使用django-background-tasks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆