我目前正在将 django 与 celery 一起使用,一切正常。
但是,如果服务器过载,我希望能够通过检查当前安排的任务数量,让用户有机会取消任务。
我怎样才能做到这一点?
我正在使用 Redis 作为代理。
我刚发现这个: Retrieve list of tasks in a queue in Celery
这在某种程度上与我的问题有关,但我不需要列出任务,只需计算它们 :)
最佳答案
下面是如何使用与代理无关的 celery 获取队列中消息的数量。
通过使用 connection_or_acquire
,您可以利用 celery 的内部连接池,最大限度地减少与代理的打开连接数。
celery = Celery(app)
with celery.connection_or_acquire() as conn:
conn.default_channel.queue_declare(
queue='my-queue', passive=True).message_count
您还可以扩展 Celery 以提供此功能:
from celery import Celery as _Celery
class Celery(_Celery)
def get_message_count(self, queue):
'''
Raises: amqp.exceptions.NotFound: if queue does not exist
'''
with self.connection_or_acquire() as conn:
return conn.default_channel.queue_declare(
queue=queue, passive=True).message_count
celery = Celery(app)
num_messages = celery.get_message_count('my-queue')
关于python - Django Celery 获取任务计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18631669/