【问题标题】:how to run django cron job with which function如何使用哪个功能运行 django cron 作业
【发布时间】: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 函数,但是如何......

【问题讨论】:

    标签: python django cron


    【解决方案1】:

    你可以考虑 celery 和 rabbitmq

    这个想法是:在您的应用程序中创建一个名为 tasks.py 的文件,然后将代码放在那里:

    # tasks.py
    from celery import task
    
    @task
    def your_task_for_async_job(data):
        # todo
    

    只需调用该函数,它就会异步为您完成工作..

    Here 是 Celery 的文档,您还可以在其中找到如何使用 django 等进行设置。

    希望,这会有所帮助

    【讨论】:

    • 是的,谢谢我读到了芹菜,但我有一个问题;我不知道在 todo 部分放什么
    • @mikebraa 你把你想异步运行的代码放了
    • 哦,我明白了,所以在我的情况下,它会像 get_score 方法吗?
    • 因为我要排名运行
    • @mikebraa 你可能想投票并接受这个作为答案;)
    猜你喜欢
    • 2016-06-14
    • 2018-08-06
    • 2015-03-08
    • 2011-09-27
    • 2014-12-23
    • 2014-04-04
    • 2021-05-10
    • 2020-01-22
    • 1970-01-01
    相关资源
    最近更新 更多