python - Celery .delay() 同步工作,不延迟

标签 python django asynchronous rabbitmq celery

我有一个带有 Celery 背景和周期性任务的 Django 项目。我一年前启动了工作进程,周期性任务运行良好。但是,我刚刚发现调用异步函数主服务器代码不起作用,apply_async()/delay() 导致函数的同步执行就像不使用它们一样.我该如何解决这个问题?我的 celery 版本是 4.2。这是我的 Celery 设置文件:

import os
from celery import Celery
from django.conf import settings

broker_url = 'amqp://<user>:<password>@localhost:5672/{project}'
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyProject.settings')

app = Celery('<project>', broker=broker_url)

app.config_from_object('django.conf:settings')
app.conf.update (
    CELERY_TASK_SERIALIZER='json',
    CELERY_ACCEPT_CONTENT=['json'],
    CELERY_RESULT_SERIALIZER='json',
    CELERYD_HIJACK_ROOT_LOGGER=False,
    BROKER_URL=broker_url,
    CELERY_RESULT_BACKEND='djcelery.backends.database.DatabaseBackend',
    CELERY_ALWAYS_EAGER=True,
)

这是我的测试代码:

from general.celery import app
from time import sleep

@app.task
def fun():
    for i in range(5):
        print('Sleeping')
        sleep(2)
    print('Awake')

def test():
    print('Begin')
    fun.apply_async(countdown=10)
    print('End')

它导致立即输出:

Begin
Sleeping
...

我还检查了 Celery 的 inspect:

from celery.task.control import inspect
print(inspect().stats())

它描述了以下状态:

{
    'broker': {
        'failover_strategy': 'round-robin',
        'ssl': False,
        'transport': 'amqp',
        'heartbeat': 120.0,
        'transport_options': {},
        'insist': False,
        'alternates': [],
        'connect_timeout': 4,
        'userid': '<user>',
        'hostname': '127.0.0.1',
        'login_method': 'AMQPLAIN',
        'port': 5672,
        'uri_prefix': None,
        'virtual_host': '<project>'
    },
    'total': {},
    'prefetch_count': 8,
    'clock': '2299',
    'pool': {
        'put-guarded-by-semaphore': False,
        'max-concurrency': 2,
        'max-tasks-per-child': 'N/A',
        'writes': {
            'avg': '0.00%',
            'inqueues': {
                'total': 2,
                'active': 0
            },
            'total': 0,
            'raw': '',
            'all': '',
            'strategy': None
        },
        'timeouts': [0, 0],
        'processes': [28728, 28729]
    },
    'pid': 28722,
    'rusage': {
        'stime': 0.3959,
        'idrss': 0,
        'maxrss': 57220,
        'inblock': 2552,
        'minflt': 24279,
        'majflt': 3,
        'msgsnd': 0,
        'ixrss': 0,
        'nswap': 0,
        'nivcsw': 31,
        'isrss': 0,
        'nvcsw': 3326,
        'utime': 2.492,
        'msgrcv': 0,
        'nsignals': 0,
        'oublock': 0
    }
}

最佳答案

您在 app.conf.update() 调用中显式设置了 CELERY_ALWAYS_EAGER=True ( docs for 3.1 ),因此 Celery 以同步模式执行。

它已被弃用并重命名为 task_always_eager ( docs for latest 4.2 ) 但您的 Celery v4.2 仍然可以识别它

关于python - Celery .delay() 同步工作,不延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54062577/

相关文章:

python - 在 DataFrame 中多次拆分字符串

python - 在指定范围内查找系列中两个数字的索引的算法

python - 正则表达式 django url

python - 如何设置 Atom 的脚本来运行 Python 3.x 脚本?与 Windows 7 Pro x64 的组合可能是问题所在吗?

python - 在 python 2.7.* 中将 TLS1.2 与 ftplib 结合使用

asp.net-mvc - 为什么 MVC Post (ViewModel) 不会使用异步返回更新后的表单?

c# - 将任务添加到 List<Task> 执行它们使 Task.WhenAll() 变得多余

c# - 为什么 Blazor UI 组件在删除事件后没有更新?

python - Django 数据库关系 - TypeError : 'ManyToOneRel' object is not iterable

django - 如何传递一个url作为include的参数