【问题标题】:How to user Schedule Library to run function every minute如何用户计划库每分钟运行一次功能
【发布时间】:2019-12-27 07:59:50
【问题描述】:

当我使用 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

【问题讨论】:

标签: python django django-rest-framework schedule


【解决方案1】:
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 install 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'

【讨论】:

  • periodic_task 未定义。当从 celery 导入时,它说不能导入 periodic_task
  • 仍然出现错误:未定义名称“periodic_task”,请分享文档链接。
  • 点安装芹菜
猜你喜欢
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-12
  • 1970-01-01
  • 2023-02-16
  • 2023-03-16
相关资源
最近更新 更多