如何使用时间表库每分钟运行一次功能

时间:2019-12-27 07:59:50

标签: python django django-rest-framework schedule

当我使用 Schedule (library link)每1分钟运行一次功能时。它工作正常,但我的其他URL无法正常工作。仅计划功能起作用。

#import scheduler library
import schedule
import time    

#update every hour global table no of players and totol payouts
def updateTotalPayoutsAndTotalPlayers():
    try:
        querysetGlobal = Global.objects.filter().first()
        querysetUser = Players.objects.filter(is_active=1).count()
        querysetTotalPayouts = Game.objects.filter(gameStatusId=3).aggregate(Sum('pot'))
        totalPayouts = querysetTotalPayouts['pot__sum']
        # print("total payouts : ",totalPayouts)
        querysetGlobal.totalPlayers = querysetUser
        querysetGlobal.totalPayouts = 0 if totalPayouts==None else totalPayouts

        querysetGlobal.save()
        # print("completed task......")

    except Exception as e:
        print("error updating payouts and no of players : ", e) 


#update globals table called ever one minute
schedule.every(1).minutes.do(updateTotalPayoutsAndTotalPlayers)

while True:
    schedule.run_pending()
    time.sleep(1) 

在其他API正常工作的同时删除 时。但我的时间表无法执行。

运行服务器我使用了命令: python manage.py runserver

1 个答案:

答案 0 :(得分:0)

from celery import shared_task
@shared_task(bind=True, default_retry_delay=10, max_retries=5)
    def my_func(self):
        ***some code***

或者尝试类似的事情:

@periodic_task(run_every=timedelta(seconds=60))
def my_func():
    ***some code***

在Linux / Windows / Mac上安装Redis服务器之前 并使 pip安装redis

在您的设置中:

# Redis/Celery application definition
REDIS_HOST = '127.0.0.1'
REDIS_PORT = '6379'
BROKER_URL = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0'
BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600}
CELERY_RESULT_BACKEND = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0'