python - Django Celery 获取任务计数

标签 python django redis celery

我目前正在将 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/

相关文章:

php - 如何在PHP中使用Redis?

Redis - 如何将 zrange 查询的结果存储为另一个有序集

javascript - 具有某些功能的发送按钮

python - 使用polyval时加载网页的问题,使用numpy的polyfit

Django - 显示一个 ModelForm 外键字段

django - 使用模型的 __unicode__ 作为管理表单中的搜索字段

ruby-on-rails - 我可以在 heroku 上使用相同的 Redis (to go) 实例来解决不同的问题吗?

python - 在 Django : How to serialize dict object to json?

python - 如何在不拆分字符串的情况下展平列表?

python - Pandas :根据条件将新列映射到现有列