2016-01-17 41 views
1

我有一個需要cron作業的應用程序。具體而言,對於排名部分,我需要我的文件同步運行,以便在後臺更改分數。這是我的代碼。 我有rank.py在我的utils的文件夾如何使用哪個函數運行django cron作業

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功能....

回答

1

你可以考慮芹菜和RabbitMQ的

的理念是:在你的應用程序創建一個名爲tasks.py有文件你把代碼:

# tasks.py 
from celery import task 

@task 
def your_task_for_async_job(data): 
    # todo 

只是調用函數,它asyncly做這項工作對你..

Here是芹菜的文檔,你會發現其中還如何使用Django等設置它。

希望,這有助於

+0

耶謝謝我讀了芹菜,但我有問題;我不知道該怎麼把部分 –

+0

@mikebraa你把你想要異步運行的代碼 – doniyor

+0

哦,我看到了,所以在我的情況下,它會像get_score方法嗎? –