[英]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.