Celery + Python: 在另一个任务中排队耗时的任务
Celery + Python: Queue time consuming tasks within another task
我想查询一个 api(这很耗时),其中包含很多项目(~100),但不是一次查询所有项目。相反,我希望查询之间有一点延迟。
我目前拥有的是一个异步执行并迭代查询并在每次迭代后等待一段时间的任务:
@shared_task
def query_api_multiple(values):
delay_between_queries = 1
query_results = []
for value in values:
time.sleep(delay_between_queries)
response = query_api(value)
if response['result']:
query_results.append(response)
return query_results
我的问题是,当多个请求进入时,第二个请求会在第一个请求完成后执行,还是在第一个请求仍在 运行 时执行?当它们不同时执行时,我该如何实现?
您不应该使用 time.sleep
,而是限制您的任务速率:
Set the rate limit for this task type (limits the
number of tasks that can be run in a given time frame).
The rate limits can be specified in seconds, minutes or hours by
appending “/s”, “/m” or “/h” to the value. Tasks will be evenly
distributed over the specified time frame.
Example: “100/m” (hundred tasks a minute). This will enforce a minimum
delay of 600ms between starting two tasks on the same worker instance.
因此,如果您想将其限制为每秒 1 个查询,请尝试以下操作:
@shared_task(rate_limit='1/s')
def query_api_multiple(values):
...
是的,如果您创建多个任务,那么它们可能会同时 运行。
如果您想限制每个时间段 运行 的任务数量,您可以使用 celery 基于任务类型进行速率限制。或者,如果您需要比 celery 提供的 OOtB 更大的灵活性,您可以使用像 redis 这样的东西结合 celery 重试来实现速率限制模式。
我想查询一个 api(这很耗时),其中包含很多项目(~100),但不是一次查询所有项目。相反,我希望查询之间有一点延迟。
我目前拥有的是一个异步执行并迭代查询并在每次迭代后等待一段时间的任务:
@shared_task
def query_api_multiple(values):
delay_between_queries = 1
query_results = []
for value in values:
time.sleep(delay_between_queries)
response = query_api(value)
if response['result']:
query_results.append(response)
return query_results
我的问题是,当多个请求进入时,第二个请求会在第一个请求完成后执行,还是在第一个请求仍在 运行 时执行?当它们不同时执行时,我该如何实现?
您不应该使用 time.sleep
,而是限制您的任务速率:
Set the rate limit for this task type (limits the number of tasks that can be run in a given time frame).
The rate limits can be specified in seconds, minutes or hours by appending “/s”, “/m” or “/h” to the value. Tasks will be evenly distributed over the specified time frame.
Example: “100/m” (hundred tasks a minute). This will enforce a minimum delay of 600ms between starting two tasks on the same worker instance.
因此,如果您想将其限制为每秒 1 个查询,请尝试以下操作:
@shared_task(rate_limit='1/s')
def query_api_multiple(values):
...
是的,如果您创建多个任务,那么它们可能会同时 运行。
如果您想限制每个时间段 运行 的任务数量,您可以使用 celery 基于任务类型进行速率限制。或者,如果您需要比 celery 提供的 OOtB 更大的灵活性,您可以使用像 redis 这样的东西结合 celery 重试来实现速率限制模式。