【问题标题】:How to periodically repeat a function until success in background in Django?如何定期重复一个函数,直到在Django的后台成功?
【发布时间】:2019-12-01 22:33:25
【问题描述】:

我正在开发一个 Django 项目。我想向外部服务器发出 http 请求。但有时外部服务器返回 5xx。我想在后台重试请求,直到它返回 200。我该怎么做? 这是我想做的伪代码:

response = requests.post(url, json=param)

if response.status_code == 200:
    # do something
elif response.status_code >= 500:
    # schedule task to retry every 30 seconds until success

【问题讨论】:

标签: python django scheduling periodic-task


【解决方案1】:

由于下载任务不是同步任务,您需要一个任务队列来归档您的目标。

Celery 是分布式任务队列,可以很容易地与 Django 集成。

您可以像这样创建下载任务:

from proj.celery import app

@app.task(bind=True)
def download(self, url, param):
    response = requests.post(url, json=param)
    if response.status_code == 200:
        # do something
        ...
    elif response.status_code >= 500:
        # schedule task to retry every 30 seconds until success
        raise self.retry(countdown=30)

调用你的任务:

download.apply_async(('YOUR DOWNLOAD URL', None))

关于芹菜的参考资料:

  1. Celery task usage
  2. How to integrate celery with into django

【讨论】:

    【解决方案2】:

    这样的事情可以解决问题:

    import time
    
    RETRY_TIME = 30
    
    referenceTime = time.time()
    
    while(1):
        currentTime = time.time()
        dt = currentTime - referenceTime
    
        if(dt > RETRY_TIME):
            referenceTime += RETRY_TIME
            print("hello")
    
            #   do your request here
    
            if(response.status_code == 200):
                break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      相关资源
      最近更新 更多