简体   繁体   English

如何使用哪个功能运行django cron作业

[英]how to run django cron job with which function

I have an app that needs a cron job. 我有一个需要预约工作的应用程序。 specifically, for ranking part I need my file to run synchronously so the score changes in the background. 具体来说,为了对部分进行排名,我需要我的文件同步运行,以便分数在后台更改。 Here is my code. 这是我的代码。 I have rank.py in my utils folder 我的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)

And I have the two functions under Post model, inside models.py 在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))

Problem is I'm not sure how to run cron job for this. 问题是我不确定如何为此运行cron作业。 I've seen http://arunrocks.com/building-a-hacker-news-clone-in-django-part-4/ and it looks like I need to create another file and another function to make the whole thing run. 我看过http://arunrocks.com/building-a-hacker-news-clone-in-django-part-4/ ,看来我需要创建另一个文件和另一个函数来使整个程序运行。 again and again./but what function?How do I use cron job for my code? 一次又一次。/但是什么功能?如何在我的代码中使用cron job? I saw there are many applications that allow me to do this, but I'm just not sure which funcction I need to use and how I should use. 我看到有许多应用程序允许我执行此操作,但是我不确定我需要使用哪种功能以及如何使用。 my guess is I need to run get_score function in models.py but how.... 我的猜测是我需要在models.py中运行get_score函数,但是如何...

you may consider celery and rabbitmq 你可能会考虑芹菜和rabbitmq

the idea is: in your app you create a file called tasks.py and there you put the code: 这个想法是:在您的应用中,创建一个名为task.py的文件,然后在其中放置代码:

# tasks.py
from celery import task

@task
def your_task_for_async_job(data):
    # todo

just call the function and it does the job for you asyncly.. 只需调用该函数,它就会为您异步完成工作。

Here is the documentation for Celery, you find there also how to set it up with django etc.. 是Celery的文档,您还可以找到如何使用django等进行设置。

hope, this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM