简体   繁体   English

如何在执行芹菜任务时停止它,并在一段时间后继续执行?

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

I have the following celery task(simplified), which interacts with Twitter API. 我有以下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

I want to be able to pause task for some time when the rate limit is hit, and resume the execution from the point where it left off. 我希望能够在达到速率限制时将任务暂停一段时间,并从中断的位置继续执行。 (Or throw an error and retry the task, passing in additional kwargs). (或者抛出一个错误,然后重试该任务,并传入其他kwarg)。 How can this be accomplished? 如何做到这一点?

You can just retry your task when you catch a 429 error code : 当捕获到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

Note that I added bind=True in your task decorator and self as parameter in the definition of your task to be able to do self.retry when you get a 429. 请注意,我在任务装饰器中添加了bind=True ,并在任务定义中将self作为参数添加到了429中,以便能够执行self.retry

in retry use the argument countdown to say when you want the task to be retried (in seconds). retry使用countdown参数表示您希望重试任务的时间(以秒为单位)。 Here I chose 15min (twitter API rate limits) 在这里,我选择了15分钟(Twitter API速率限制)

You can find more infos about retrying in the celery documentation : 您可以在celery文档中找到有关重试的更多信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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