简体   繁体   中英

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

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

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. 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. again and again./but what function?How do I use cron job for my code? 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....

you may consider celery and rabbitmq

the idea is: in your app you create a file called tasks.py and there you put the code:

# 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..

hope, this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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