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
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.
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:
- 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. - Your task looks strange. You should declare it as global function in separate file and pass
id
of model inside it, fetch object byid
do calculations and save your object.
来源:https://stackoverflow.com/questions/30816134/how-to-use-django-background-tasks