【发布时间】:2016-01-17 15:15:01
【问题描述】:
我有一个需要 cron 作业的应用。具体来说,对于排名部分,我需要我的文件同步运行,以便分数在后台发生变化。这是我的代码。 我的 utils 文件夹中有 rank.py
from datetime import datetime, timedelta
from math import log
epoch = datetime(1970, 1, 1)
def epoch_seconds(date):
td = date - epoch
return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
def score(ups, downs):
return ups - downs
def hot(ups, downs, date):
s = score(ups, downs)
order = log(max(abs(s), 1), 10)
sign = 1 if s > 0 else -1 if s < 0 else 0
seconds = epoch_seconds(date) - 1134028003
return round(sign * order + seconds / 45000, 7)
我在 Post 模型下有两个函数,在 models.py 里面
def get_vote_count(self):
vote_count = self.vote_set.filter(is_up=True).count() - self.vote_set.filter(is_up=False).count()
if vote_count >= 0:
return "+ " + str(vote_count)
else:
return "- " + str(abs(vote_count))
def get_score(self):
"""
:return: The score calculated by hot ranking algorithm
"""
upvote_count = self.vote_set.filter(is_up=True).count()
devote_count = self.vote_set.filter(is_up=False).count()
return hot(upvote_count, devote_count, self.pub_date.replace(tzinfo=None))
问题是我不确定如何为此运行 cron 作业。我见过http://arunrocks.com/building-a-hacker-news-clone-in-django-part-4/,看起来我需要创建另一个文件和另一个函数来让整个事情运行起来。一次又一次。/但是什么功能?如何为我的代码使用 cron 作业?我看到有很多应用程序允许我这样做,但我只是不确定我需要使用哪个功能以及应该如何使用。我的猜测是我需要在 models.py 中运行 get_score 函数,但是如何......
【问题讨论】: