簡體   English   中英

如何在執行芹菜任務時停止它,並在一段時間后繼續執行?

[英]How to stop celery task while it is being executed and continue the execution after some time?

我有以下celery任務(簡化),它與Twitter API交互。

@app.task
def get_followers(screen_name, **kwargs):
    cursor = kwargs.get('cursor', -1)
    followers = kwargs.get('followers', [])
    while True:
        response = twitter_api.call('followers', 'ids', screen_name=screen_name, cursor=cursor)
        if response.status_code == '429': # RATE LIMIT EXCEEDED
            # do something here

        cursor = response.json()['next_cursor']
        if cursor == 0: # we're done
            break
    return followers

我希望能夠在達到速率限制時將任務暫停一段時間,並從中斷的位置繼續執行。 (或者拋出一個錯誤,然后重試該任務,並傳入其他kwarg)。 如何做到這一點?

當捕獲到429錯誤代碼時,您可以僅重試任務:

@app.task(bind=True)
def get_followers(self, screen_name, **kwargs):
    cursor = kwargs.get('cursor', -1)
    followers = kwargs.get('followers', [])
    while True:
        response = twitter_api.call('followers', 'ids', screen_name=screen_name, cursor=cursor)
        if response.status_code == '429': 
            # RATE LIMIT EXCEEDED
            self.retry(countdown=15*60)

        cursor = response.json()['next_cursor']
        if cursor == 0: # we're done
            break
    return followers

請注意,我在任務裝飾器中添加了bind=True ,並在任務定義中將self作為參數添加到了429中,以便能夠執行self.retry

retry使用countdown參數表示您希望重試任務的時間(以秒為單位)。 在這里,我選擇了15分鍾(Twitter API速率限制)

您可以在celery文檔中找到有關重試的更多信息:

http://docs.celeryproject.org/en/latest/userguide/tasks.html#retrying

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM