how to use django-background-tasks

不打扰是莪最后的温柔 提交于 2019-12-03 16:35:58

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.

There is a difference between django-background-task and django-background-tasks. django-background-task was unmaintained and incompatible with newer Django versions. We updated and extended it with new features a while ago and maintaining the new backward compatible package django-background-tasks on Github. The new django-background-tasks app can be downloaded or installed from the PyPI.

You should run python manage.py process_tasks as described here. You can add it to crontab to execute periodically.

UPD:

  1. You don't need to run process_tasks using crontab cause this command internally sleeps every 5 seconds (this value is configurable) and then again checks whether there is any task to run.
  2. Your task looks strange. You should declare it as global function in separate file and pass id of model inside it, fetch object by id do calculations and save your object.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!